c#Linq方法使用GroupBy和Select(c# Linq Method with GroupBy and Select)
我有以下型号:
public class HeadCount { public int Id { get; set; } public int ContractId { get; set; } public string FiscalYear { get; set; } public string TaskOrder { get; set; } public decimal ContractHours { get; set; } public int PersonId { get; set; } public string CompanyName { get; set; } public string UserId { get; set; } public int ClinAssignId { get; set; } }使用标准的sql,我在SSMS中运行以下脚本:
select personid, sum(contracthours) as hours from headcounts where personid != 0 group by personid我正在努力将其转换为LINQ menthod调用。 这是我试过的:
var results = _context.HeadCounts .GroupBy(p => p.PersonId) .Select(n => new {personid = n.Key, hours = n.Sum(ContractHours)});它不喜欢Sum中的ContractHours 。 我甚至尝试过n.ContractHours
我究竟做错了什么?
I have the following model:
public class HeadCount { public int Id { get; set; } public int ContractId { get; set; } public string FiscalYear { get; set; } public string TaskOrder { get; set; } public decimal ContractHours { get; set; } public int PersonId { get; set; } public string CompanyName { get; set; } public string UserId { get; set; } public int ClinAssignId { get; set; } }Using standard sql, I have the following script I run in SSMS:
select personid, sum(contracthours) as hours from headcounts where personid != 0 group by personidI am stubbling trying to convert this to a LINQ menthod call. This is what I tried:
var results = _context.HeadCounts .GroupBy(p => p.PersonId) .Select(n => new {personid = n.Key, hours = n.Sum(ContractHours)});It does not like the ContractHours in the Sum. I have even tried n.ContractHours
What am I doing wrong?
最满意答案
如果集合不是原始数字集合,则Sum采用选择器,因此您需要:
n.Sum(p => p.ContractHours)Thanks to Robs comment in the original question, this was the answer I was looking for.
更多推荐
发布评论