0

我有以下查询:

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

    }

但它很丑。还有其他方法吗?
谢谢。

4

2 回答 2

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

}
于 2012-07-12T11:29:42.917 回答
1

关于什么:

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

顺便说一句,使用 IsNullOrWhiteSpace

于 2012-07-12T11:25:44.007 回答