c#Linq方法使用GroupBy和Select(c# Linq Method with GroupBy and Select)

编程入门 行业动态 更新时间:2024-10-10 23:19:04
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 personid

I 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.

更多推荐

本文发布于:2023-07-29 03:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1311978.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Linq   GroupBy   Method   Select

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!