1. 程式人生 > >【轉載】C#中使用OrderBy和ThenBy等方法對List集合進行排序

【轉載】C#中使用OrderBy和ThenBy等方法對List集合進行排序

derby 轉載 排序。 sha esc ews 個人 類的定義 orderby

在C#的List操作中,針對List對象集合的排序我們可以使用OrderBy、OrderByDescending、ThenBy、ThenByDescending等方法按照特定的對象屬性進行排序,其中Orderby表示按指定的第一個屬性升序排序,OrderByDescending表示按指定的第一個屬性降序排序,如果排序需要使用到不止一個條件的時候,可先使用OrderBy或者OrderByDescending方法排序完成後,再在方法鏈中調用ThenBy或者ThenByDescending對第二個條件排序,ThenBy會進行升序排序,ThenByDescending則是進行降序排序。

例如一個訂單的Order類的定義如下:

 public class Order
  {
        public string DepCode { set; get; }

        public string DepName { set; get; }

        public decimal Amount { set; get; }
 }

針對訂單類的List集合orderList對象進行排序,排序規則為:先按科室編碼DepCode升序排序,而後根據訂單金額Amount進行降序排序。則相應的語句如下:

 orderList = orderList.OrderBy(t => t.DepCode).ThenByDescending(t => t.Amount).ToList();

上述語句中t => t.DepCode的形式是Lambda表達式的寫法,t代表orderList集合中的Order對象實體。

備註:原文轉載自博主個人技術站點IT技術小趣屋,原文鏈接C#中使用OrderBy和ThenBy等方法對List集合進行排序_IT技術小趣屋。

【轉載】C#中使用OrderBy和ThenBy等方法對List集合進行排序