方法链的构造函数(LINQ)

时间:2012-07-12 11:22:13

标签: c# linq

我有以下查询:

private IEnumerable<EventSchedule> GetTodaySchedules(string tab)
{
    var today = DateTime.Now.Date;

    var result = Database.EventSchedules.Where(s => 
    s.RecurrenceStart.Value.Date <= today && 
    s.RecurrenceStart.Value.TimeOfDay > today.TimeOfDay &&
    s.RecurrenceEnd.Value.Date >= today &&
    s.BaseEvent.EndShow > DateTime.Now &&
    s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
    s.BaseEvent.EventsCategories.Any(c => c.EventCategory.Name == tab)).ToList();
}

此查询从EventSchedule表中选择今天的事件。问题在于,有时tab为空,此查询不返回任何记录。我可以这样写:

private IEnumerable<EventSchedule> GetTodaySchedules(string tab)
    {
        var today = DateTime.Now.Date;
        if(string.IsNullOrWhiteSpace(tab))
        {
             var result = Database.EventSchedules.Where(s => 
             s.RecurrenceStart.Value.Date <= today && 
             s.RecurrenceStart.Value.TimeOfDay > today.TimeOfDay &&
             s.RecurrenceEnd.Value.Date >= today &&
             s.BaseEvent.EndShow > DateTime.Now &&
             s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value).ToList();
        {
        else
        {
             var result = Database.EventSchedules.Where(s => 
             s.RecurrenceStart.Value.Date <= today && 
             s.RecurrenceStart.Value.TimeOfDay > today.TimeOfDay &&
             s.RecurrenceEnd.Value.Date >= today &&
             s.BaseEvent.EndShow > DateTime.Now &&
             s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
             s.BaseEvent.EventsCategories.Any(c => c.EventCategory.Name == tab)).ToList();
        }

    }

但它很难看。还有另一种方法吗?
感谢。

2 个答案:

答案 0 :(得分:2)

这个怎么样......你也可以像Henrik所展示的那样三元运算符......

private IEnumerable<EventSchedule> GetTodaySchedules(string tab)
{
     var today = DateTime.Now.Date;
     var result = Database.EventSchedules.Where(s => 
     s.RecurrenceStart.Value.Date <= today && 
     s.RecurrenceStart.Value.TimeOfDay > today.TimeOfDay &&
     s.RecurrenceEnd.Value.Date >= today &&
     s.BaseEvent.EndShow > DateTime.Now &&
     s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value);
     if(string.IsNullOrWhiteSpace(tab))
     {
         var result1 = result.Where(s => s.BaseEvent.EventsCategories.Any(c => c.EventCategory.Name == tab))).ToList();
     }

}

答案 1 :(得分:1)

怎么样:

&& (string.IsNullOrWhiteSpace(tab) || s.BaseEvent.EventsCategories.Any(c => c.EventCategory.Name == tab))

BTW,使用IsNullOrWhiteSpace