LINQ标准查询运算符执行方式-非流式处理

LINQ的延迟执行方式分两种,一种是流式,另一种是非流式。非流式处理运算符必须先读取所有源数据,然后才能生成结果元素。

非流式处理的运算符包括:GroupBy、OrderBy、OrderByDescending、Reverse、ThenBy、ThenByDescending

GroupBy

List<Pet> petsList =    new List<Pet>{ new Pet { Name="Barley", Age=8.3 },           new Pet { Name="Boots", Age=4.9 },           new Pet { Name="Whiskers", Age=1.5 },           new Pet { Name="Daisy", Age=4.3 } };//public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source,//Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector);var query = petsList.GroupBy(pet => Math.Floor(pet.Age),pet=>pet.Age,(key,ages)=>new {     key,    count=ages.Count(),    min=ages.Min(),    max=ages.Max()});         foreach (var result in query){    Console.WriteLine(result);               }

View Code

OrderBy,升序

Pet[] pets = { new Pet { Name="Barley", Age=8 },       new Pet { Name="Boots", Age=4 },       new Pet { Name="Whiskers", Age=1 } };//public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source,//Func<TSource, TKey> keySelector);IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);foreach (Pet pet in query){    Console.WriteLine("{0} - {1}", pet.Name, pet.Age);}

View Code

OrderByDescending,降序

List<decimal> decimals =new List<decimal> { 6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m };IEnumerable<decimal> query =    decimals.OrderByDescending(num=>num);foreach (decimal num in query){    Console.WriteLine(num);}

View Code

Reverse,反转序列中元素的顺序

char[] apple = { 'a', 'p', 'p', 'l', 'e' };var reversed = apple.Reverse();foreach (char chr in reversed){    Console.Write(chr + " ");}Console.WriteLine();

View Code

ThenBy 按升序对序列中的元素执行后续排序

string[] fruits = { "grape", "passionfruit", "banana", "mango",          "orange", "raspberry", "apple", "blueberry" };//public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IOrderedEnumerable<TSource> source, //    Func<TSource, TKey> keySelector);IEnumerable<string> query =    fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);foreach (string fruit in query){    Console.WriteLine(fruit);}

View Code

ThenByDescending 按降序对序列中的元素执行后续排序

string[] fruits = { "apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE" };//public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(this IOrderedEnumerable<TSource> source,//Func<TSource, TKey> keySelector);IEnumerable<string> query =    fruits    .OrderBy(fruit => fruit.Length)    .ThenByDescending(fruit => fruit[0]);foreach (string fruit in query){    Console.WriteLine(fruit);}

View Code

(0)

相关推荐