2013-07-04 22 views
1

我想LINQ到組通過日期,但顯示在文本LINQ組通過,然後顯示(DD MMM)

這裏的日期時間是我的代碼

var groups = _uow.Orders.GetAll() 
      .Where(x => x.Created > baselineDate) 
      .GroupBy(x => x.Created.ToString("yyyy-MM-dd")); 

var orders = new 
     { 
      Day = groups.Select(g => g.Key).ToArray(), 
      Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(), 
     }; 

結果(不好放在圖表的標籤)

{"Day": [2, 3, 4, 5], "Total": [9999.00, 9999.00, 9999.00, 9999.00] } 

但我想這(每月)

"Day": ['Jan', Feb', 'Mar', 'Apr'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] } 

或每日

"Day": ['Jan 1', 'Jan 2', 'Jan 3', 'Jan 4'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] } 

請諮詢我則DateTime.ToString(),我可以玩。

謝謝大家。

回答

2

This question描述如何將日期時間轉換爲月份的字符串名稱。

編輯:爲EF,我們做任何字符串邏輯之前拉一切到內存:

var orders = _uow.Orders.GetAll() 
    .Where(x => x.Created > baselineDate) 
    // pull into memory here, since we won't be making the result set any smaller and 
    // we want to use DateTime.ToString(), which EF won't compile to SQL 
    .AsEnumerable() 
    // this will group by the whole date. If you only want to group by part of the date, 
    // (e. g. day or day, month), you could group by x => x.Date.Month or the like 
    .GroupBy(x => x.Date) 
    .Select(g => new { 
     // or use just "MMM" for just the month 
     Dates = g.Select(g => g.Key.ToString("MMM d")).ToArray(), 
     Total = ... 
    }); 
+1

這應該是一個評論 –

+0

是啊,我知道如何使用的ToString( 「MMMM」)或任何別人stringFormat。但是當我使用LINQ進行分組時,它不起作用。 – riseres

+0

@riseres是否將linq用於對象? Linq to SQL? EF? NHibernate的? – ChaseMedallion

0

您需要使用的功能是EF能夠理解並轉化爲SQL,如EntityFunctions.TruncateTime。這是您更新的代碼:

var groups = _uow.Orders.GetAll() 
      .Where(x => x.Created > baselineDate) 
      .GroupBy(x => EntityFunctions.TruncateTime(x.Created)); 

然後使用字符串格式化只是在輸出中,但要確保你價值已恢復到.NET之後做,使用AsEnumerable切換到Linq- to-Objects:

var orders = new 
     { 
      Day = groups.Select(g => g.Key) 
         .AsEnumerable() 
         .Select(x => x.ToString("MMM d")) 
         .ToArray(), 
      Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(), 
     }; 
2

謝謝大家的幫助。 我找到了答案。

添加

.AsEnumerable() 

.GroupBy(x => x.Created.ToString("MMM d")); 

這裏是完整的代碼

var groups = _uow.Orders.GetAll() 
      .Where(x => x.Created > baselineDate) 
      .AsEnumerable() 
      .GroupBy(x => x.Created.ToString("MMM d")); 

     var orders = new 
     { 
      Day = groups.Select(g => g.Key).ToArray(), 
      Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(), 
     };