【转载】C#中使用OrderBy和ThenBy等方法对List集合进行排序

在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技术小趣屋

猜你喜欢

转载自www.cnblogs.com/xu-yi/p/10852624.html
今日推荐