如何将具有相同类型项目的列表列表合并到单个项目列表中?

Dav*_*.ca 190 c# linq lambda

问题很混乱,但如下面的代码所述,它更加清晰:

   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 = ???
Run Code Online (Sandbox Code Playgroud)

不确定是否可以使用C#LINQ或Lambda?

基本上,我如何连接或" 展平 "列表列表?

Jar*_*Par 415

使用SelectMany扩展方法

list = listOfList.SelectMany(x => x).ToList();
Run Code Online (Sandbox Code Playgroud)

  • 我想知道有多少人写过他们自己的"Flatten"扩展没有意识到SelectMany是如何工作的? (68认同)
  • @SwimBikeRun SelectMany用于获取IEnumerable的TSources,将列表中的每个TSource转换为一个IEnumerable的TResults,然后将所有这些IEnumerables连接成一个大的.在这种情况下,您有一个要开始的列表列表,因此如果您想要连接它们,从TSource(它是一个IEnumerable of TResults)映射到IEnumerable的TResults的函数是标识函数(x => x).这实际上只是一个特殊情况,您不需要将每个TSource转换为列表的额外步骤,因为它已经是一个列表. (7认同)
  • @TusharKukreti当然,只需使用`list.SelectMany(x => x.SelectMany(y => y)).ToList();` (4认同)
  • 为什么需要 x =&gt; x 才能起作用?我通常会看到类似 x =&gt; x +1 的东西,但不会看到 x =&gt; x。 (2认同)

Joe*_*ung 13

这是C#集成语法版本:

var items =
    from list in listOfList
    from item in list
    select item;
Run Code Online (Sandbox Code Playgroud)

  • 'double from'与SelectMany相同... SelectMany可能是最强大的LINQ方法(或查询运算符).要了解原因,谷歌"LINQ SelectMany Monad"你会发现比你想知道的更多. (4认同)
  • 在谷歌搜索"LINQ SelectMany Monad"时不要包含引号,否则它只会引导你回到这里. (3认同)

IRB*_*BMe 12

你是说这个吗?

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);
Run Code Online (Sandbox Code Playgroud)

结果是: 9 9 9 1 2 3 4 5 6


Arm*_*ian 5

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

list.SelectMany(x => x.SelectMany(y => y)).ToList();
Run Code Online (Sandbox Code Playgroud)

这已发布在评论中,但在我看来确实值得单独回复。