The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.
SelectMany(<selector>) method For example, SelectMany() can turn a two-dimensional array into a single sequence of values, as shown in this example: int[][] arrays = { new[] {1, 2, 3}, new[] {4}, new[] {5, 6, 7, 8}, new[] {12, 14} }; // Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 } IEnumerable<int> result = arrays.
Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.
You want to use the SelectMany
extension method.
var residences = details.SelectMany(d => d.AppForm_Residences).ToList();
Use SelectMany
var all = residences.SelectMany(x => x.AppForm_Residences);
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 . . .
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With