开发者

Ordering by two date fields, whichever one is more recent

I want my objects ordered by latest date, either by updated date or created date, whichever o开发者_开发知识库ne 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!


I don't know if I have well understood what you're asking but here is my solution:

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

Tested with a class named MyClass:

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

And with these values:

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)}
};

The result is:

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


I tried this query in LINQPad with the Northwind DB, and it worked fine:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜