SelectMany 和 Select的区别

许多人容易混淆了SelectMany和Select的用法,作为扩展方法它们的区别何在呢?

如果我们看这两个扩展函数的定义很容易明白——Select是把要遍历的集合IEnumerable<T>逐一遍历,每次返回一个T,合并之后直接返回一个IEnumerable<T>,而SelectMany则把原有的集合IEnumerable<T>每个元素遍历一遍,每次返回一个IEnumerable<T>,把这些IEnumerable<T>的“T”合并之后整体返回一个IEnumerable<T>。

上述红色部分标记了它们最大的差别。因此我们可以说一般情况下SelectMany用于返回一个IEnumerable<IEnumerable<T>>的“嵌套”返回情况(把每个IEnumerable<T>合并后返回一个整体的IEnumerable<T>)。因此在嵌套的时候往往可以节省代码,例如输出带有以下的集合:

[C#]

List<List<int>> numbers = new List<List<int>>()
{
  new List<int>{1,2,3},
  new List<int>{4,5,6},
  new List<int>{7,8,9}
};

[VB.NET]

Dim numbers As New List(Of List(Of Integer))() From { _
    New List(Of Integer)() From { _
        1, _
        2, _
        3 _
    }, _
    New List(Of Integer)() From { _
        4, _
        5, _
        6 _
    }, _
    New List(Of Integer)() From { _
        7, _
        8, _
        9 _
    } _
}

通常情况下要遍历一个嵌套的数组,我们不得不采用二重循环(for或者foreach),不过现在我们可以借助SelectMany进行简化处理(把每个内嵌的List取出,因为每一个List都是IEnumerable<T>,合并成一个大的IEnumerable<T>)。简化如下:

[C#]

var result = numbers.SelectMany(collection=>collection);

foreach(var item in result)
{
  ………………
}

[VB.NET]

Dim result = numbers.SelectMany(Function(collection) collection)

For Each item As var In result
………………
Next
原文地址:https://www.cnblogs.com/ServiceboyNew/p/2609764.html