开发者

LINQ DateTimeOffset comparison with today

I have a class with a DateTimeOffset property:

public class Sample 
{
    public DateTimeOffset expires { get; set; }
}

and eventually a collection of them:

IEnumerable<Sample> collection;

2 questions:

  1. What is the best way to create a method that returns al开发者_开发百科l the Sample items from the collection where expires is greater than now and is still today (i.e. before midnight)?

  2. What is the best way to return all Sample items from the collection where expires is in the next 24 hours?


// greater than now, still today            
collection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.Date == DateTime.Today);

// expires in the next 24 hours
collection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.DateTime < DateTime.Now.AddHours(24));


var list1 = 
    collection.Where
        (c => c.expires.DateTime > DateTime.Now && 
              c.expires.DateTime < DateTime.Today.AddDays(1));

var list2 = 
    collection.Where
        (c => c.expires.DateTime >= DateTime.Now && 
              c.expires.DateTime <= DateTime.Now.AddHours(24));


It's a good practice to "cache" the calculated values for performance, otherwise it would be calculated in each loop(as Where does a loop internally):

DateTime tomorrow = DateTime.Today.AddDays(1);
DateTime now = DateTime.Now;
DateTime next24hrs = now.AddHours(24);
IEnumerable<Sample> next24HoursSamples = collection.Where(sample=>sample.expires>now && sample.expires<next24hrs).ToList();
IEnumerable<Sample> sameDaySamples = next24HoursSamples.Where(sample=>sample.expires>=now && sample.expires<tomorrow).ToList();

Notice that the sameDay list is retrieved from the already filtered list(same day is a subset of the next 24 hours),so there are less items to filter on.

EDIT: I updated the code to use an immediate query execution model, as @danijels warns about deferred execution.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜