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>)。因此在嵌套的时候往往可以节省代码,例如输出带有以下的集合:

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<T>,合并成一个大的IEnumerable<T>)。简化如下:

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

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


 

 

 

posted on 2012-11-04 22:15  terry.zh  阅读(2278)  评论(0编辑  收藏  举报