253

Seems like this is the kind of thing that would have already been answered but I'm unable to find it.

My question is pretty simple, how can I do this in one statement so that instead of having to new the empty list and then aggregate in the next line, that I can have a single linq statement that outputs my final list. details is a list of items that each contain a list of residences, I just want all of the residences in a flat list.

var residences = new List<DAL.AppForm_Residences>();
details.Select(d => d.AppForm_Residences).ToList().ForEach(d => residences.AddRange(d));
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
Jarrett Widman
  • 6,329
  • 4
  • 23
  • 32
  • 1
    Possible duplicate of [How to merge a list of lists with same type of items to a single list of items?](http://stackoverflow.com/questions/1191054/how-to-merge-a-list-of-lists-with-same-type-of-items-to-a-single-list-of-items) – Dzyann Dec 11 '15 at 15:40

4 Answers4

406

You want to use the SelectMany extension method.

var residences = details.SelectMany(d => d.AppForm_Residences).ToList();
Noldorin
  • 144,213
  • 56
  • 264
  • 302
66

Use SelectMany

var all = residences.SelectMany(x => x.AppForm_Residences);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
52

Here is a sample code for you:

List<int> listA = new List<int> { 1, 2, 3, 4, 5, 6 };

List<int> listB = new List<int> { 11, 12, 13, 14, 15, 16 };

List<List<int>> listOfLists = new List<List<int>> { listA, listB };

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

foreach (int item in flattenedList)
{
    Console.WriteLine(item);
}

And the out put will be:

1
2
3
4
5
6
11
12
13
14
15
16
Press any key to continue . . .
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
Wilson Wu
  • 1,790
  • 19
  • 13
35

And for those that want the query expression syntax: you use two from statements

var residences = (from d in details from a in d.AppForm_Residences select a).ToList();
Sean B
  • 11,189
  • 3
  • 27
  • 40