[英]How to merge a list of lists with same type of items to a single list of items?
問題很混亂,但如下面的代碼所述,它更加清晰:
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 = ???
不確定是否可以使用C#LINQ或Lambda?
基本上,我如何連接或“ 展平 ”列表列表?
使用SelectMany擴展方法
list = listOfList.SelectMany(x => x).ToList();
你是說這個嗎?
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
這是C#集成語法版本:
var items =
from list in listOfList
from item in list
select item;
對於List<List<List<x>>>
等,請使用
list.SelectMany(x => x.SelectMany(y => y)).ToList();
這已在評論中發布,但在我看來,它確實值得單獨回復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.