【问题标题】:How to merge a collection of collections in Linq如何在 Linq 中合并集合的集合
【发布时间】:2010-09-24 04:31:16
【问题描述】:

我希望能够将 IEnumerable<IEnumerable<T>> 融合到 IEnumerable<T> 中(即将所有单独的集合合并为一个)。 Union 运算符仅适用于两个集合。有什么想法吗?

【问题讨论】:

    标签: linq collections linq-to-objects


    【解决方案1】:

    试试

    var it = GetTheNestedCase();
    return it.SelectMany(x => x);
    

    SelectMany 是一种 LINQ 转换,它本质上说“对于集合中的每个项目,返回集合的元素”。它将一个元素变成多个元素(因此是 SelectMany)。它非常适合将集合的集合分解为一个平面列表。

    【讨论】:

    • LINQ 开箱即用的功能总是让我感到惊讶。 :)
    【解决方案2】:
    var lists = GetTheNestedCase();
    return
        from list in lists
        from element in list
        select element;
    

    是另一种使用 C# 3.0 查询表达式语法的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多