【问题标题】:LINQ OrderBy query fails to sort properly by descending dateTimeLINQ OrderBy 查询无法按 dateTime 降序正确排序
【发布时间】:2017-10-13 16:56:03
【问题描述】:

我有一个简单的 linq 查询,它根据 dateTime 降序和升序对记录进行排序。由于某种原因,它在 13:00:00 时失败了。

sortedrecords = sortedrecords.OrderByDescending(x => x.DateTime).ThenBy(x=>x.Time);

它应该对 2PM、1PM、12PM 进行排序。但是下午 1 点的记录出现在最后。

我的查询有问题吗?任何建议都会有所帮助。

谢谢

降序排列(失败)

2017 年 10 月 12 日下午 2:00:56
2017 年 10 月 12 日下午 2:00:50
2017 年 10 月 12 日下午 12:29:41
2017 年 10 月 12 日下午 12:28:32
2017 年 10 月 12 日下午 12:27:35
2017 年 10 月 12 日上午 11:21:35
2017 年 10 月 12 日上午 11:14:16
2017 年 10 月 12 日下午 1:49:28
2017 年 10 月 12 日下午 1:43:23

升序排列(正确)

2017 年 10 月 12 日下午 12:27:35
2017 年 10 月 12 日下午 12:28:32
2017 年 10 月 12 日下午 12:29:41
2017 年 10 月 12 日下午 1:43:23
2017 年 10 月 12 日下午 1:49:28
2017 年 10 月 12 日下午 2:00:50
2017 年 10 月 12 日下午 2:00:56

【问题讨论】:

  • 您的x.DateTimex.Time 属性是什么?请展示sortedrecords 对象的类是什么样的。
  • 试试OrderByDescending(x => x.DateTime.Date).ThenBy(x=>x.Time);
  • 其实你应该检查DateTime.Ticks属性。您是否使用具有不同 TimeZone 规范的 DateTime?如果不涉及时区,那么一个简单的解决方法是使用DateTime.Ticks 进行排序
  • @SantoshKumar 在这里没有部分回答问题我建议您编辑您的原始帖子以显示sortedrecords 对象的类的样子。
  • yes it is string DateTime 类型。它只需要在呈现给用户时是一个字符串(如在表单或网页中)。我希望它们也不会作为字符串保存在数据存储中......

标签: c# .net linq sorting datetime


【解决方案1】:

由于您没有具体说明对象类型、列类型、数据库(假设您使用的是一个)、为什么使用 .Net 类类型名称作为列名称等。我假设您正在处理匿名List 中的对象:

sortedrecords = sortedrecords.OrderByDescending(x => DataTime.Parse(x.DateTime));

【讨论】:

    猜你喜欢
    • 2011-07-17
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    相关资源
    最近更新 更多