JStellato JStellato - 23 days ago 6
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

db.tbl
.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

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:

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