如何同类型项目的列表清单合并项目的一个列表?(How to merge a list of list

2019-06-17 16:58发布

现在的问题是混乱的,但如下面的代码说明它是更明确:

   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或拉姆达?

从本质上讲,我怎么可以连接或“ 扁平化 ”名单列表?

Answer 1:

使用扩展的SelectMany方法

list = listOfList.SelectMany(x => x).ToList();


Answer 2:

你的意思呢?

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



Answer 3:

下面是C#语法整合版本:

var items =
    from list in listOfList
    from item in list
    select item;


Answer 4:

对于List<List<List<x>>>等,使用

list.SelectMany(x => x.SelectMany(y => y)).ToList();

这已被张贴在评论,但它确实值得在我看来,一个单独的答复。



文章来源: How to merge a list of lists with same type of items to a single list of items?
标签: c# linq lambda