开发者

Linq, Lambda and nullable DateTime combination question

I have a Schedule class:

public class Schedule
{

 .....

 public DateTime? StartDate{get;set;}
 public DateTime? EndDate{get;set;}

 ....

}

I would like to get the list of started Schedule objects from an IEnumerable list in the optimal way using linq or lambda.


NOTE: An empty date value means infinity here. How开发者_开发百科ever, unspecified schedule period (empty start and end dates) means schedule is not started ..


schedules.Where(s => s.StartDate < DateTime.Now
                     || (s.StartDate == null && s.EndDate != null));

This assumes you actually want what you said – all started schedules, including those that already ended.

Also, you might want to change the way you represent unspecified schedule period, probably by adding a bool for that. If null means infinity, it should always mean infinity.


var started =
    from s in schedules
    let startDate = s.StartDate ?? DateTime.MaxValue
    let endDate = s.EndDate ?? DateTime.MinValue
    where startDate <= DateTime.Now
    && endDate > DateTime.Now
    select s;


bool IsStarted(Schedule schedule) {
   // Assuming that ended schedules should be excluded
   return schedule.StartDate != null && schedule.StartDate > DateTime.Now
       && (schedule.EndDate==null || schedule.EndDate < Datetime.Now);
}

items.Where(IsStarted);

If possible, it would not be the worst idea, to make IsStarted a property of your Schedule class. In that case you would have to use:

items.Where(i => i.IsStarted);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜