简体   繁体   English

实体框架-计算具有相同名称的记录

[英]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. 因此,如果我有两个名为Erik的客户和三个名为Roberts的记录。 The function would return two Eriks and three Robers. 该函数将返回两个Eriks和三个Robers。

You could use the group by part of linq for this 您可以为此使用linq的一部分

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. 这将为您提供一组对象,这些对象的属性为“名称”,而属性为“ Count”,即您拥有多少个具有该特定名称的客户。 Then you can use that information as needed 然后您可以根据需要使用该信息

How about this? 这个怎么样?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM