按两个日期字段排序,以较新的为准

时间:2011-03-10 17:02:08

标签: c# .net linq linq-to-sql

我希望我的对象按最新日期排序,可以是更新日期,也可以是创建日期,以较新的日期为准。下面我的代码的问题是未更新的对象(为空)出现在底部。

public IQueryable<MyObject> GetMyObjects()
{
    return from obj in _db.MyObjects
           orderby obj.UpdatedDate descending, obj.CreatedDate descending
           select obj;
}

即使某个对象没有更新日期,如果这些对象的更新日期小于该对象的创建日期,它仍应显示在具有更新日期的其他对象之前。我怎样才能做到这一点?基本上,我想按最新日期订购,并使用更新日期或创建日期,以较晚者为准。

我的linq代码应如何更改以实现此目的?谢谢!

2 个答案:

答案 0 :(得分:4)

我在LINQPad中使用Northwind DB尝试了这个查询,它运行良好:

from o in Orders
orderby o.RequiredDate > o.ShippedDate ? o.RequiredDate : o.ShippedDate
select new
{
    o.RequiredDate,
    o.ShippedDate
}

答案 1 :(得分:3)

我不知道我是否很清楚你在问什么,但这是我的解决方案:

return from myclass in classes
       let updated = myclass.Updated ?? myclass.Created
       orderby updated descending
       select myclass;

使用名为MyClass的类进行测试:

class MyClass
{
    public DateTime? Updated { get; set; }
    public DateTime Created { get; set; }
}

使用这些值:

MyClass[] classes = 
{
    new MyClass() { Created = DateTime.Now.AddDays(12)},
    new MyClass() { Created = DateTime.Now.AddDays(-5), Updated = DateTime.Now.AddDays(3)},
    new MyClass() { Created = DateTime.Now},
    new MyClass() { Created = DateTime.Now.AddDays(2), Updated = DateTime.Now.AddDays(10)},
    new MyClass() { Created = DateTime.Now},
    new MyClass() { Created = DateTime.Now.AddDays(1), Updated = DateTime.Now.AddDays(1)},
    new MyClass() { Created = DateTime.Now},
    new MyClass() { Created = DateTime.Now.AddDays(20), Updated = DateTime.Now.AddDays(4)}
};

结果是:

Updated = null - Created = 22/03/2011
Updated = 20/03/2011 - Created = 12/03/2011
Updated = 14/03/2011 - Created = 30/03/2011
Updated = 13/03/2011 - Created = 05/03/2011
Updated = 11/03/2011 - Created = 11/03/2011
Updated = null - Created = 10/03/2011
Updated = null - Created = 10/03/2011
Updated = null - Created = 10/03/2011