FCL研究-LINQ-System.Linq Enumerable

   .net 里面集合操作极为方便,尤其是实现了IEnumerable接口的集合,一直在使用,系统的研究一下集合的操作也是极好的。

类型 操作符名称
投影操作符 Select,SelectMany
限制操作符 Where
排序操作符 OrderBy,OrderByDescending,ThenBy,ThenByDescending,Reverse
联接操作符 Join,GroupJoin
分组操作符 GroupBy
串联操作符 Concat
聚合操作符 Aggregate,Average,Count,LongCount,Max,Min,Sum
集合操作符 Distinct,Union,Intersect,Except
生成操作符 Empty,Range,Repeat
转换操作符 AsEnumerable,Cast,OfType,ToArray,ToDictionary,ToList,ToLookup
元素操作符 DefaultIfEmpty,ElementAt,ElementAtOrDefault,First,Last,FirstOrDefault, LastOrDefault,Single,SingleOrDefault
相等操作符 SequenceEqual
量词操作符 All,Any,Contains
分割操作符 Skip,SkipWhile,Take,TakeWhile

 投影操作符

  投影操作就是我们常用的Select和SelectMany,刚接触的话是很容易搞混的。

Select是把要遍历的集合IEnumerable<T>逐一遍历,每次返回一个T,合并之后直接返回一个IEnumerable<T>

SelectMany则把原有的集合IEnumerable<T>每个元素遍历一遍,每次返回一个IEnumerable<T>,把这些IEnumerable<T>的“T”合并之后整体返回一个IEnumerable<T>

     

看下MSN的图:地址

测试代码:

List<Bouquet> bouquets = new List<Bouquet>() {
        new Bouquet { Flowers = new List<string> { "sunflower", "daisy", "daffodil", "larkspur" }},
        new Bouquet{ Flowers = new List<string> { "tulip", "rose", "orchid" }},
        new Bouquet{ Flowers = new List<string> { "gladiolis", "lily", "snapdragon", "aster", "protea" }},
        new Bouquet{ Flowers = new List<string> { "larkspur", "lilac", "iris", "dahlia" }}
    };

    // *********** Select ***********            
    IEnumerable<List<string>> query1 = bouquets.Select(bq => bq.Flowers);

    // ********* SelectMany *********
    IEnumerable<string> query2 = bouquets.SelectMany(bq => bq.Flowers);

    Console.WriteLine("Results by using Select():");
    // Note the extra foreach loop here.
    foreach (IEnumerable<String> collection in query1)
        foreach (string item in collection)
            Console.WriteLine(item);

    Console.WriteLine("
Results by using SelectMany():");
    foreach (string item in query2)
        Console.WriteLine(item);
View Code
作者:BangQ

http://www.cnblogs.com/BangQ/

 

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
说明:本文以“现状”提供且没有任何担保,同时也没有授予任何权利。 | This posting is provided "AS IS" with no warranties, and confers no rights.
珍爱生命,Leave here!
原文地址:https://www.cnblogs.com/BangQ/p/3981117.html