2012-07-12 57 views
0

的我有以下查詢:構造方法鏈(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(); 
     } 

    } 

但它很醜。還有其他方法嗎?
謝謝。

回答

1

什麼:

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

BTW,使用IsNullOrWhiteSpace

2

這個怎麼樣,你可以三元運算符一樣顯示亨裏克·太......

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

}