【发布时间】:2010-09-27 21:27:08
【问题描述】:
我正在使用 LINQ to EF 并有以下 LINQ 查询:
var results = (from x in ctx.Items
group x by x.Year into decades
orderby decades.Count() descending
select new { Decade = decades.Key, DecadeCount = decades.Count() });
所以这种方式让我到达了我想去的地方,因为我得到了按年份细分的项目以及当年的项目数量。 (即 2001 - 10, 1975 - 15, 2005 - 5, 1976 - 1)我真正想做的事情是按十年分解它们(即 2000s - 15, 1970s - 16)。
如何在 Linq 语句的 group 子句的“by”部分中具有“计算字段”。我想我想要的基本上是这样的:
var results = (from x in ctx.Items
group x by (x => x.Year.Value.ToString().Substring(0, 3) + "0s") into decades
orderby decades.Count() descending
select new { Decade = decades.Key, DecadeCount = decades.Count() });
或更一般的语法,以便我可以进行一些更复杂的评估/计算来进行分组。有什么想法吗?
编辑(更新):
(x => x.Year.Value.ToString().Substring(0, 3) + "0s") - 不起作用 - "LINQ to Entities 无法识别方法 'System.String ToString() ' 方法,并且这个方法不能翻译成 store 表达式。”
(x.Year / 10 * 10) - 功能有效(谢谢) - 唯一的“问题”是 's' 不在末尾(即 1970 与 1970 年代)
有没有在 by 子句中放置一个函数?即按 this.ManipulateYear(x.Year) 将 x 分组为几十年...或... x => x.Year.Value.ToString().Substring(0,3) + "0s" ??最好有一些技术(例如调用函数或使用 lambda 表达式),这样我就可以涵盖我能想到的任何情况。
再次感谢大家对此的帮助。
【问题讨论】:
标签: c# .net linq .net-3.5 linq-to-entities