2011-06-13 68 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