LINQ的延遲執行方式分兩種,一種是流式,另一種是非流式。非流式處理運算符必須先讀取所有源數據,然後才能生成結果元素。 非流式處理的運算符包括:GroupBy、OrderBy、OrderByDescending、Reverse、ThenBy、ThenByDescending GroupBy List ...
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