1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| var orders = new List<Order>(){ new Order {CustomerId = 3, OrderDate = new DateTime(2011, 10, 9), Total = 2940}, new Order {CustomerId = 2, OrderDate = new DateTime(2012, 10, 10), Total = 3849}, new Order {CustomerId = 1, OrderDate = new DateTime(2011, 12, 1), Total = 500}, new Order {CustomerId = 1, OrderDate = new DateTime(2012, 2, 28), Total = 1234}, new Order {CustomerId = 2, OrderDate = new DateTime(2012, 5, 20), Total = 9520} };
Console.WriteLine("原排序"); foreach (var e in orders) Console.WriteLine(e.ToString()); Console.WriteLine();
Console.WriteLine("遞增排序"); var singleOrderAsc = orders.OrderBy(e => e.CustomerId); foreach (var e in singleOrderAsc) Console.WriteLine(e.ToString()); Console.WriteLine();
Console.WriteLine("遞減排序"); var singleOrderDesc = singleOrderAsc.OrderByDescending(e => e.CustomerId); foreach (var e in singleOrderDesc) Console.WriteLine(e.ToString()); Console.WriteLine();
Console.WriteLine("多欄位遞減排序"); var OrderDesc = singleOrderAsc .OrderByDescending(e => e.CustomerId) .ThenByDescending(e => e.Total); foreach (var e in OrderDesc) Console.WriteLine(e.ToString()); Console.WriteLine();
Console.WriteLine("多欄位之先遞減再遞增排序"); var OrderDescAsc = OrderDesc .OrderByDescending(e => e.CustomerId) .ThenBy(e => e.Total); foreach (var e in OrderDescAsc) Console.WriteLine(e.ToString()); Console.WriteLine();
public class Order { public int CustomerId { get; set; } public DateTime OrderDate { get; set; } public double Total { get; set; }
public override string ToString() { return string.Format("CustomerId = {0}, OrderDate = {1}, Total = {2}", CustomerId, OrderDate, Total); } }
|