Pytanie jest mylące, ale jest o wiele bardziej jasne, jak opisano w następujących kodach:
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 = ???
Nie jesteś pewien, czy jest to możliwe przy użyciu C # LINQ lub Lambda?
Zasadniczo, jak mogę połączyć lub „spłaszczyć„lista list?
Odpowiedzi:
323 dla odpowiedzi № 1Użyj metody rozszerzenia SelectMany
list = listOfList.SelectMany(x => x).ToList();
10 dla odpowiedzi nr 2
Masz na myśli to?
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);
Prowadzi do: 9 9 9 1 2 3 4 5 6
10 dla odpowiedzi nr 3
Oto wersja składni zintegrowanej w języku C #:
var items =
from list in listOfList
from item in list
select item;