Erik Larsson
Erik Larsson

Reputation: 2709

Entity Framework - Count records with the same name

I have a customer table filled with customer detail and I would like to count all the records in that table and return how many records exist in the table for each name.

So if I have two customers with name Erik, and three records with name Roberts. The function would return two Eriks and three Robers.

Upvotes: 0

Views: 749

Answers (2)

Jeff Camera
Jeff Camera

Reputation: 5554

How about this?

Customers.GroupBy(x => x.Name)
    .Select(x => new { Name = x.Key, Count = x.Count() })

Upvotes: 2

Rune FS
Rune FS

Reputation: 21752

You could use the group by part of linq for this

from grp in (
    from customer in customers
    group customer.Name by Customer.Name
 select new {Name = grp.Key, Count = grp.Count()};

That will give you an set of objects with a property "Name" and a property "Count" the count being how many customers with that particular name you have. Then you can use that information as needed

Upvotes: 2

Related Questions