带有 GroupBy 和 Select 的 c# Linq 方法
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)});
不喜欢求和中的ContractHours
。我什至试过 n.ContractHours
我做错了什么?
如果集合不是原始数字集合,Sum
采用选择器,因此您需要:
n.Sum(p => p.ContractHours)
感谢 Robs 在原始问题中的评论,这就是我正在寻找的答案。
我有以下型号:
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)});
不喜欢求和中的ContractHours
。我什至试过 n.ContractHours
我做错了什么?
Sum
采用选择器,因此您需要:
n.Sum(p => p.ContractHours)
感谢 Robs 在原始问题中的评论,这就是我正在寻找的答案。