nmit026
nmit026

Reputation: 3392

Make a list of lists a list

I have a List<List<CustomType>>. Each List<CustomType> contains only 1 CustomType. How do I make my List<List<CustomType>> a List<CustomType>?

Upvotes: 2

Views: 78

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74365

As noted, you can use SelectMany(). Given something like this:

List<List<CustomType>> listOfLists = Init() ;

You can simply say:

List<CustomType> flattenedList = listOfLists.SelectMany().ToList() ;

but, since you know that each of nested lists contains a single item, you could simply say something like either of these:

  • List<CustomType> flattenedList = listOfLists.Select( x => x.First() ).ToList() ;

  • List<CustomType> flattenedList = listOfLists.Select( x => x[0] ) ;

Upvotes: 3

Related Questions