.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("\nResults by using SelectMany():"); foreach (string item in query2) Console.WriteLine(item);
时间: 2024-11-06 07:13:32