光脚丫学LINQ(003):排序结果集

视频演示:http://u.115.com/file/f2e2959888

通常可以很方便地将返回的数据进行排序。orderby 子句将使返回的序列中的元素按照被排序的类型的默认比较器进行排序。例如,下面的查询可以扩展为按 Name 属性对结果进行排序。因为 Name 是一个字符串,所以默认比较器执行从 A 到 Z 的字母排序。

NorthwindDataContext db = new NorthwindDataContext();   
  
var LondonCustomers = from Customer in db.Customers   
                      where Customer.City == "London"  
                      orderby Customer.ContactName   
                      select Customer;   
  
foreach (var Customer in LondonCustomers)   
{   
    Console.WriteLine("---------------------");   
    Console.WriteLine("Customer ID : {0}", Customer.CustomerID);   
    Console.WriteLine("Customer Name : {0}", Customer.ContactName);   
    Console.WriteLine("City : {0}", Customer.City);   
}  
NorthwindDataContext db = new NorthwindDataContext();

var LondonCustomers = from Customer in db.Customers
                      where Customer.City == "London"
                      orderby Customer.ContactName
                      select Customer;

foreach (var Customer in LondonCustomers)
{
    Console.WriteLine("---------------------");
    Console.WriteLine("Customer ID : {0}", Customer.CustomerID);
    Console.WriteLine("Customer Name : {0}", Customer.ContactName);
    Console.WriteLine("City : {0}", Customer.City);
} 

若要按相反顺序(从 Z 到 A)对结果进行排序,请使用 orderby…descending 子句。

原文地址:https://www.cnblogs.com/GJYSK/p/1863790.html