Problem
The question seems perplexing, but as described in the following codes, it becomes much clearer:
List<List<T>> listOfList;
// add three lists of List<T> to listOfList, for example
/* listOfList = new {
{ 1, 2, 3}, // list 1 of 1, 3, and 3
{ 4, 5, 6}, // list 2
{ 7, 8, 9} // list 3
};
*/
List<T> list = null;
// how to merger all the items in listOfList to list?
// { 1, 2, 3, 4, 5, 6, 7, 8, 9 } // one list
// list = ???
Not sure if you can do it with C# LINQ or Lambda?
In other words, how can I concatenate or “flatten” a collection of lists?
Asked by David.Chu.ca
Solution #1
Use the SelectMany extension method to get a list of all the people in your group.
list = listOfList.SelectMany(x => x).ToList();
Answered by JaredPar
Solution #2
The C# integrated syntax version is as follows:
var items =
from list in listOfList
from item in list
select item;
Answered by Joe Chung
Solution #3
Is this what you mean?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
9 9 9 1 2 3 4 5 6 9 9 9 1 2 3 4 5 6 9 9 9 1 2 3 4 5 6 9 9 9 1
Answered by IRBMe
Solution #4
For List>> etc., make use of
list.SelectMany(x => x.SelectMany(y => y)).ToList();
This was mentioned in a comment, but it merits its own response, in my opinion.
Answered by Arman
Post is based on https://stackoverflow.com/questions/1191054/how-to-merge-a-list-of-lists-with-same-type-of-items-to-a-single-list-of-items