按两个日期字段排序,以较新的日期字段为准
我希望我的对象按最新日期排序,可以按更新日期或创建日期(以较新的日期为准)。下面我的代码的问题是未更新的对象(为空)出现在底部。
public IQueryable<MyObject> GetMyObjects()
{
return from obj in _db.MyObjects
orderby obj.UpdatedDate descending, obj.CreatedDate descending
select obj;
}
即使某个对象没有更新日期,它仍然应该显示在其他有更新日期的对象之前,前提是这些对象的更新日期小于该对象的创建日期。我怎样才能实现这个目标?基本上,我想按最新日期排序,并使用更新日期或创建日期(以较晚者为准)。
我的 linq 代码应该如何更改才能实现此目的?谢谢!
I want my objects ordered by latest date, either by updated date or created date, whichever one is more recent. The problem with my code below is that objects that are not updated (which are null) appear at the bottom.
public IQueryable<MyObject> GetMyObjects()
{
return from obj in _db.MyObjects
orderby obj.UpdatedDate descending, obj.CreatedDate descending
select obj;
}
Even if an object doesn't have an updated date, it should still appear before other objects that do have an updated date, if those objects' updated dates are less that this object's created date. How can I achieve this? Basically, I want to order by latest date and use either the updated date or created date whichever one is later.
How should my linq code be changed to achieve this? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道我是否很好地理解了您的要求,但这是我的解决方案:
使用名为
MyClass
的类进行测试:并使用这些值:
结果是:
I don't know if I have well understood what you're asking but here is my solution:
Tested with a class named
MyClass
:And with these values:
The result is:
我在 LINQPad 中使用 Northwind DB 尝试了这个查询,效果很好:
I tried this query in LINQPad with the Northwind DB, and it worked fine: