【问题标题】:How to merge a list of lists with same type of items to a single list of items?如何将具有相同类型项目的列表列表合并到单个项目列表中?
【发布时间】:2010-11-14 12:46:23
【问题描述】:

这个问题令人困惑,但如以下代码所述,它更清楚:

   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?

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

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

    使用 SelectMany 扩展方法

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

    【讨论】:

    • 我想知道有多少人编写了自己的“Flatten”扩展程序却没有意识到 SelectMany 的工作原理?
    • 为什么需要 x => x 才能工作?我通常会看到 x = > x +1 之类的东西,但不会看到 x = > x。
    • @SwimBikeRun SelectMany 用于获取 TSources 的 IEnumerable,将列表中的每个 TSource 转换为 TResults 的 IEnumerable,然后将所有这些 IEnumerables 连接成一个大的。在这种情况下,您有一个要启动的列表列表,因此如果您想将它们连接起来,从 TSource(它是 TResults 的 IEnumerable)映射到 TResults 的 IEnumerable 的函数是标识函数 (x => x)。这实际上只是一种特殊情况,您不需要将每个 TSource 转换为列表的额外步骤,因为它已经是一个列表。
    • @JaredPar 我们可以将此逻辑应用于列表>> 吗?
    • @TusharKukreti 当然,使用list.SelectMany(x =&gt; x.SelectMany(y =&gt; y)).ToList();
    【解决方案2】:

    这是 C# 集成语法版本:

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

    【讨论】:

    • 有点混乱,但很好。这是怎么回事? var items = from item in (from list of listOflist select list) select item
    • 'double from' 与 SelectMany 相同... SelectMany 可能是最强大的 LINQ 方法(或查询运算符)。要了解原因,谷歌“LINQ SelectMany Monad”,你会发现比你想知道的更多。
    • 在谷歌搜索“LINQ SelectMany Monad”时不要包含引号,否则它只会将您引导回此处。
    【解决方案3】:

    你是这个意思吗?

    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

    【讨论】:

    • 或者您可以使用 list.AddRange() 而不是 Concat() 将合并的项目添加到现有列表中。
    【解决方案4】:

    对于List&lt;List&lt;List&lt;x&gt;&gt;&gt;等,使用

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2020-05-20
      • 1970-01-01
      • 2011-07-19
      • 2017-09-28
      • 2023-01-08
      • 2017-06-10
      相关资源
      最近更新 更多