Problem
This appears to be the type of question that has already been answered, but I can’t find it.
My issue is quite straightforward: how can I do this in a single statement, rather than creating an empty list and then aggregating in the following line, so that I may have a single linq expression that outputs my final list? I just want all of the dwellings in a flat list, so details is a list of items that each contain a list of residences.
var residences = new List<DAL.AppForm_Residences>();
details.Select(d => d.AppForm_Residences).ToList().ForEach(d => residences.AddRange(d));
Asked by Jarrett Widman
Solution #1
SelectMany is the extension method you want to utilize.
var residences = details.SelectMany(d => d.AppForm_Residences).ToList();
Answered by Noldorin
Solution #2
Use SelectMany
var all = residences.SelectMany(x => x.AppForm_Residences);
Answered by JaredPar
Solution #3
For your convenience, I’ve included a sample code:
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 here’s what you’ll get as a result:
1
2
3
4
5
6
11
12
13
14
15
16
Press any key to continue . . .
Answered by Wilson Wu
Solution #4
For those who are interested in the query expression syntax, two from statements are used.
var residences = (from d in details from a in d.AppForm_Residences select a).ToList();
Answered by Sean B
Post is based on https://stackoverflow.com/questions/1145558/linq-list-of-lists-to-single-list