2015-06-26 66 views
1

我想根據傳遞給我的函數的int來區分我的查詢。目前我有這個非常哈克解決方案:在運行時按日/周/月/年動態分組

`.GroupBy(occurrence => new { date = 
       // Bucket by day. 
       timeBucket == 0 ? DbFunctions.TruncateTime(occurrence.occurrenceDate) : 
       // Bucket by week. 
       timeBucket == 1 ? DbFunctions.AddDays(DbFunctions.CreateDateTime(occurrence.occurrenceDate.Year, 1, 1, 0, 0, 0), 7*(occurrence.occurrenceDate.DayOfYear/7)) : 
       // Bucket by month. 
       timeBucket == 2 ? DbFunctions.TruncateTime(DbFunctions.CreateDateTime(occurrence.occurrenceDate.Year, occurrence.occurrenceDate.Month, 1, 1, 1, 1)) : 
       // Bucket by year. 
       DbFunctions.TruncateTime(DbFunctions.CreateDateTime(occurrence.occurrenceDate.Year, 1, 1, 1, 1, 1)), 
       type = occurrence.type })` 

的我是如何計算的日期的細節並不是我來說太重要(但隨時反正給予幫助)。我想避免爲數據庫中的每一行查看此case語句。無論如何避免這樣做?我已經嘗試了各種像使用表達式的解決方案,但我不能回到我想要的對象,因爲表達式樹必須參...

如果任何人有一個解決方案,將不勝感激。

謝謝!

回答

0

定義石斑魚類:

class TimeGrouper 
{ 
    public int Year { get; set; } 
    public int Month { get; set; } 
    public int Week { get; set; } 
    public int Day { get; set; } 
} 

和一個函數返回一個表達式:

using System.Data.Entity.SqlServer; 
... 
Expression<Func<Occurrence, TimeGrouper>> GetGrouper(int grouping) 
{ 
    switch (grouping) 
    { 
     case 1: 
      return o => new TimeGrouper 
         { 
          Year = o.occurrenceDate.Year 
         }; 
     case 2: 
      return o => new TimeGrouper 
         { 
          Year = o.occurrenceDate.Year, 
          Month = o.occurrenceDate.Month 
         }; 
     case 3: 
      return o => new TimeGrouper 
         { 
          Year = o.occurrenceDate.Year, 
          Week = SqlFunctions.DatePart("wk", o.StartDate).Value 
         }; 
     default: 
      return o => new TimeGrouper 
         { 
          Year = o.occurrenceDate.Year, 
          Day = SqlFunctions.DatePart("dy", o.StartDate).Value 
         }; 
    } 
} 

現在,您可以撥打

db.Occurrences.GroupBy(GetGrouper(3)); 
+0

這個工作!萬分感謝! –

0

爲什麼不這樣做(主要是僞代碼):按日期

switch(timeBucket) 
{ 
    case 0: result=query.GroupBy(...); 
    case 1: result=query.GroupBy(...); 
    case 2: result=query.GroupBy(...); 
} 
+0

我使用的方法的語法,而不是查詢語法......我一直沒能找到一種方法在LINQ to使用switch語句與方法的語法...:/ –

0

分組,月,年是很容易。星期因您的日曆周而異。

  List<DateTime> occurance = new List<DateTime>(); 
 

 
      var dayGroup = occurance.GroupBy(x => x.Date); 
 
      var yearGroup = occurance.GroupBy(x => x.Year); 
 
      var monthGroup = occurance.GroupBy(x => newKeyValuePair<int,int>(x.Month, x.Year));​