Search code examples
c#linq

Is there a way to extract list from list without making it a List<List<>> situation?


Extract list from list of lists...

I have a structure like

Struct1
{
 public int blah-blah
 public string blah-blah-blah
 public List<Struct2> problematicList
}

var problem = List<Struct1>

And I want to exctract all of Struct2's elements from a List of Struct1 Query like

List<Struct2> struct2s= 
                problem.Select(x => x.problematicList.Struct2).ToList();

gives me a list of lists, and I can't wrap my head around of how to do it corretly with a singular linq query. There must be a way, is it not?


Solution

  • What you're looking for is SelectMany.

    Using SelectMany, you would write something like the following:

    List<Struct2> struct2s = problem.SelectMany(x => x.problematicList).ToList();