Keith Clark
Keith Clark

Reputation: 609

c# Linq Method with GroupBy and Select

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?

Upvotes: 0

Views: 42

Answers (2)

Keith Clark
Keith Clark

Reputation: 609

Thanks to Robs comment in the original question, this was the answer I was looking for.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152634

Sum takes a selector if the collection is not a primitive numeric collection, so you need:

n.Sum(p => p.ContractHours)

Upvotes: 1

Related Questions