Linq Group和Count in IEnumerable

时间:2013-06-26 11:32:05

标签: asp.net-mvc linq

我的控制器中有以下LINQ查询查询我的IEnumerable Collection,当我在视图中输出结果时,分组工作,但是当我尝试在列上添加计数时,我将其分组失败。我想知道是否有人可以提供帮助,我一直在看前面的例子,但我遗漏了一些明显的东西。

Grouped //正常工作并返回分组描述

itemdetails = (from c in db.CLIENTDETAILS
                           join l in db.LOCATIONS on c.CLIENTNUMBER equals l.CLIENTNUMBER
                           where c.CLIENTNUMBER == clientNumber
                           join i in db.ITEMDETAILS on l.LOCNUMBER equals i.LOCNUMBER
                           where i.LOCNUMBER == l.LOCNUMBER
                           select i).GroupBy(it => it.DESC).Select(grp => grp.FirstOrDefault()).OrderBy(x => x.DESC)

我试图在LINQ中获取Group和Count //不能正常返回错误

itemdetails = (from c in db.CLIENTDETAILS
                           join l in db.LOCATIONS on c.CLIENTNUMBER equals l.CLIENTNUMBER
                           where c.CLIENTNUMBER == clientNumber
                           join i in db.ITEMDETAILS on l.LOCNUMBER equals i.LOCNUMBER
                           where i.LOCNUMBER == l.LOCNUMBER
                           select i).GroupBy(it => it.DESC).Select(grp => new {DESC = grp.key, Count = grp.COUNT()}).OrderBy(x => x.DESC)

这给我以下错误: - 无法将类型系统linq iorderedqueryable隐式转换为system.collections.generic.ienumerable

感谢您一如既往的帮助。

1 个答案:

答案 0 :(得分:2)

您的两个查询返回不同的数据,第一个返回类型为ItemDetail的项,而第二个查询返回匿名类型的项。

如果你想要一个匿名类型的IEnumerable,你需要使用var关键字声明它,即

var itemdetails = (from c in db.CLIENTDETAILS
                           join l in db.LOCATIONS on c.CLIENTNUMBER equals l.CLIENTNUMBER
                           where c.CLIENTNUMBER == clientNumber
                           join i in db.ITEMDETAILS on l.LOCNUMBER equals i.LOCNUMBER
                           where i.LOCNUMBER == l.LOCNUMBER
                           select i).GroupBy(it => it.DESC).Select(grp => new {DESC = grp.key, Count = grp.COUNT()}).OrderBy(x => x.DESC)