我正在使用 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)但我真正想做的是按十年(即 2000 年代 - 15、1970 年代 - 16)将它们分解。
如何在 Linq 语句的组子句的“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() ' 方法,并且此方法无法转换为存储表达式。”
(x.Year/10 * 10) - 功能正常(谢谢) - 唯一的“问题”是“s”不在末尾(即 1970 年与 1970 年代)
是否可以在 by 子句中放置一个函数?即通过 this.ManipulateYear(x.Year) 将 x 分组为几十年......或...... x => x.Year.Value.ToString().Substring(0,3) + "0s"??如果能有一些技术(例如调用函数或使用 lambda 表达式)就更好了,这样我就可以涵盖我能想到的任何情况。
再次感谢大家对此的帮助。
最佳答案
您可以使用 let
子句来避免多次计算十年:
from x in ctx.Items
group x by (x.Year / 10 * 10) into decades
let decadeCount = decades.Count()
orderby decadeCount descending
select new { Decade = decades.Key, DecadeCount = decadeCount }
关于c# - 使用 LINQ 如何按 "calculated field"进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/384004/