VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • 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);               
}
复制代码

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);
}
复制代码

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);
}
复制代码

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

复制代码
char[] apple = { 'a', 'p', 'p', 'l', 'e' };

var reversed = apple.Reverse();

foreach (char chr in reversed)
{
    Console.Write(chr + " ");
}
Console.WriteLine();
复制代码

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);
}           
复制代码

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);
}
复制代码

 

量变会引起质变。

相关教程