2011-06-13 115 views
1

我花了很多時間試圖將下面的查詢轉換爲LINQ到實體。LINQ到SQL集合函數

SELECT ItemCode, AVG([Count]) As [Count] 
FROM [tblHistory] 
GROUP BY ItemCode 
ORDER BY [Count] desc 

在我的實體框架EDMX,我有一個tblHistory與領域

{ ItemCode(int), Count(int), Date(datetime) } 

我可以組一列,並顯示特定列(在這種情況下Count),但訪問ItemCode在同樣的環境給我帶來麻煩。

其中之一,我試圖使用方法低於:

var query = from p in Context.tblHistories 
      group p by p.ItemCode into g 
      select new tblHistory 
         { 
          ItemCode = g.Key, 
          Count = from c in g select new { c.Count } 
         }; 

請讓我知道,如果需要的人誰擁有這方面的知識,我會很樂意提供更多的信息。

回答

3
tblHistories.GroupBy(p => p.ItemCode) 
     .Select(g => new { ItemCode = g.Key, Count = g.Average (c => c.Count)}) 
     .OrderByDescending(x => x.Count) 
     .AsEnumerable() 
     .Select(x => new tblHistory{ ItemCode = x.ItemCode, Count = (int)x.Count }) 
+0

應改爲'OrderByDescending'。 – Yakimych 2011-06-13 20:05:16

+0

你是對的,更正。 – Equiso 2011-06-13 20:06:49

+0

非常感謝您的回覆,我嘗試使用您提供的查詢語法,但有一個問題。我在返回IEnumerable 的函數中創建查詢。要做到這一點我有選擇新 {ItemCode = g.Key,Count = g.Average(c => c.Count)})。OrderBy(x => x.Count)並且我得到double和int之間的cast錯誤,你有任何指導,爲什麼發生這種情況?再次感謝 – Sue 2011-06-13 20:10:00