【问题标题】:Linq to sql: Order by datetime desc, then order by the time part of the data asc?Linq to sql:按datetime desc排序,然后按数据asc的时间部分排序?
【发布时间】:2018-01-23 13:59:30
【问题描述】:

这是一个快速的。
在 Linq to sql 中,我需要按日期时间字段降序排序,然后按同一日期时间字段的时间部分升序排序,有意义吗?以下是所需结果的示例:

[序列] [日期 (mm-dd-yyyy:hh-MM-ss)]
1 2008 年 3 月 13 日:10-10-02
2 2008 年 3 月 13 日:10-12-60
3 3-12-2008:12-05-55


我试过了:

return query.OrderByDescending(c=> c.Time).ThenBy(c=> c.Time.TimeOfDay);


也试过了:

query.OrderByDescending(c => c.Time).ThenBy(c => c.Time.Hour).ThenBy(c=> c.Time.Minute).ThenBy(c=> c.Time.Second);


但似乎从来没有工作过。 有什么建议吗?

【问题讨论】:

    标签: linq-to-sql


    【解决方案1】:

    使用DateTimeOfDay 属性进行排序。

    return query
       .OrderByDescending(c=> c.Time.Date)
       .ThenBy(c=> c.Time.TimeOfDay);
    

    【讨论】:

    • 哇,是的,又是同时回答
    【解决方案2】:

    问题是“时间”包含日期和时间信息,因此,已经完全排序。您必须先使用日期部分进行排序。

    return query.OrderByDescending(c=> c.Time.Date).ThenBy(c=> c.Time.TimeOfDay);
    

    未测试:)

    【讨论】:

      【解决方案3】:

      我认为 first orderByDescending 按日期时间(日期+时间)对所有内容进行排序,因此只有当您有任何具有相同时间戳的记录时,以下 orderbys 才会生效。

      试试这个

      query.OrderByDescending(c=> c.Time.Date).ThenBy(c=> c.Time.TimeOfDay)
      

      【讨论】:

        【解决方案4】:

        把它变成刻度也可以:

        return query.OrderByDescending(c=> c.Time.Ticks)
        

        【讨论】:

        • 谢谢。这实际上是唯一对我有用的答案。
        猜你喜欢
        • 1970-01-01
        • 2014-07-11
        • 2011-06-28
        • 2016-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-12
        相关资源
        最近更新 更多