我想计算通用列表中特定组的出现次数 [英] I want to count number of occurance of specific group in Generic List
问题描述
我有两个课.
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
我有以上课程的数据,请在下面检查.
I have data for above class , please check below .
List<Employee> lstEmployee = new List<Employee>();
lstEmployee.Add(new Employee() { FirstName = "Ronak", LastName = "Patel" });
lstEmployee.Add(new Employee() { FirstName = "Ronak", LastName = "Patel" });
lstEmployee.Add(new Employee() { FirstName = "Sanjay", LastName = "Patel" });
lstEmployee.Add(new Employee() { FirstName = "Ronak", LastName = "Patel" });
lstEmployee.Add(new Employee() { FirstName = "Sanjay", LastName = "Patel" });
lstEmployee.Add(new Employee() { FirstName = "Ronak", LastName = "Patel" });
lstEmployee.Add(new Employee() { FirstName = "Mohan", LastName = "Patel" });
我要过滤通用列表上方并绑定到下面的结构类中.
I want filter above generic list and bound into below structure class .
class CountEmployeeName
{
public string FirstName { get; set; }
public int CountFirstName { get; set; }
}
我想根据上面的数据像下面的示例那样绑定CountEmployeeName类对象.
I want bind CountEmployeeName class object as per above data like below sample .
FirstName CountFirstName
Ronak 4 (Ronak is 4 time in above Employee class list)
Sanjay 2 (Sanjay is 4 time in above Employee class list)
Mohan 1 (Mohan is 4 time in above Employee class list)
我想根据Employee List的给定数据,将CountEmployeeName类的Generic List像上面的输出一样绑定.
I want to bind Generic List of CountEmployeeName class like above output as per given data for Employee List .
推荐答案
使用linq group by
,然后在select
项目中使用第二种类型:
Use linq group by
and then in the select
project to your second type:
from item in lstEmployee
group item by item.FirstName into grouping
select new CountEmployeeName
{
FirstName = grouping.Key,
CountFirstName = grouping.Count()
}
在方法语法中,它将如下所示:
In method syntax it will look like this:
lstEmployee.GroupBy(item => item.FirstName)
.Select(grouping => new CountEmployeeName {
FirstName = grouping.Key,
CountFirstName = grouping.Count()
});
请注意,我建议将CountFirstName
更改为int
而不是string
Note that I'd recommend changing the CountFirstName
to an int
rather than string
这篇关于我想计算通用列表中特定组的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!