【问题标题】:How to use orderby with 2 fields in linq? [duplicate]如何在 linq 中使用 orderby 和 2 个字段? [复制]
【发布时间】:2010-01-01 21:20:30
【问题描述】:

假设我在数据库表中有这些值

id = 1
StartDate = 1/3/2010
EndDate =  1/3/2010

id = 2
StartDate = 1/3/2010
EndDate = 1/9/2010

到目前为止,我的 linq 已经有了这个 orderby

var hold = MyList.OrderBy(x => x.StartDate).ToList();

我想订购它,但也使用结束日期。

就像我想要的顺序一样

id 2
id 1

所以endDates 更大的优先。我不确定是否需要更改它以使用一些比较功能或其他东西。

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
    

    【讨论】:

      【解决方案2】:

      使用ThenByDescending:

      var hold = MyList.OrderBy(x => x.StartDate)
                       .ThenByDescending(x => x.EndDate)
                       .ToList();
      

      你也可以使用查询语法说:

      var hold = (from x in MyList
                 orderby x.StartDate, x.EndDate descending
                 select x).ToList();
      

      ThenByDescendingIOrderedEnumerable 上的扩展方法,这是OrderBy 返回的内容。另见相关方法ThenBy

      【讨论】:

      • 谢谢你——你也知道结构保持的类型吗? MyList 项目的列表?
      【解决方案3】:

      如果您有两个或更多字段要订购,请尝试以下操作:

      var soterdList = initialList.OrderBy(x => x.Priority).
                                          ThenBy(x => x.ArrivalDate).
                                          ThenBy(x => x.ShipDate);
      

      您可以使用 clasole "ThenBy" 添加其他字段

      【讨论】:

        【解决方案4】:
        MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
        

        请注意,您也可以在 OrderBy 中使用 Descending 关键字(如果需要)。所以另一个可能的答案是:

        MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);
        

        【讨论】:

          【解决方案5】:

          VB.NET

           MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)
          

            From l In MyList Order By l.StartDate Ascending, l.EndDate Descending
          

          【讨论】:

          • From l In MyList Order By l.StartDate Ascending Order By l.EndDate DescendingFrom l In MyList Order By l.StartDate Ascending, l.EndDate Descending有区别吗?
          • @Oleksandr 是的,阿卜杜勒的变种相当于只做二阶,所以不正确。
          • @John 和 @oleksandr 感谢您指出错误尚未更正
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多