JStellato JStellato - 9 months ago 40
C# Question

Linq Group By with Count and Key Name

I'm attempting to get the company name from a table in which I create the new anonymous type after a group. The query works if I comment out the "CompanyName" Line

.GroupBy(a => a.ID)
.Select(b => new {
// This line is where I need help, I want to grab the company name
CompanyName = b.GroupBy(x=>x.CustomerName).ToString(),
CustomerId = (int) b.Key,
TotalQuotes = b.Count()

Answer Source

You don't need to Group each list again.

As I suppose the CustomerName will be the same for all the entities part of a Group, you can simply take the first entity and extract from it the CustomerName:

    .GroupBy(a => a.ID)
    .Select(c => new {
        CompanyName = c.First().CustomerName,
        CustomerId = (int) c.Key,
        TotalQuotes = c.Count()