SelectMany 和 Select的区别

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

因此我们可以说一般情况下SelectMany用于返回一个IEnumerable<IEnumerable>的“嵌套”返回情况(把每个IEnumerable合并后返回一个整体的IEnumerable)。因此在嵌套的时候往往可以节省代码,例如输出带有以下的集合:

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}
};

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

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

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

from:https://blog.csdn.net/qq_29487981/article/details/83349232


原文地址:https://www.cnblogs.com/youmingkuang/p/14854092.html