• 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

    
    
  • 相关阅读:
    组合与封装
    继承与派生
    面向对象编程
    subprocess、re、logging模块
    json、pickle、collections、openpyxl模块
    python内置模块
    递归函数与模块
    生成式、面向过程、与函数式
    叠加装饰器与迭代器
    闭包函数与装饰器
  • 原文地址:https://www.cnblogs.com/youmingkuang/p/14854092.html
Copyright © 2020-2023  润新知