I want to count number of occurance of specific group in Generic List
本问题已经有最佳答案,请猛点这里访问。
我有两个班。
1 2 3 4 5 | public class Employee { public string FirstName { get; set; } public string LastName { get; set; } } |
我有以上课程的资料,请在下面核对。
1 2 3 4 5 6 7 8 | 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" }); |
我希望在泛型列表上方筛选并绑定到下面的结构类中。
1 2 3 4 5 | class CountEmployeeName { public string FirstName { get; set; } public int CountFirstName { get; set; } } |
我要根据上面的数据绑定CountEmployeeName类对象,如下面的示例。
1 2 3 4 |
我想根据员工列表的给定数据绑定上面输出的CountEmployeeName类的通用列表。
使用linq
1 2 3 4 5 6 7 | from item in lstEmployee group item by item.FirstName into grouping select new CountEmployeeName { FirstName = grouping.Key, CountFirstName = grouping.Count() } |
在方法语法中,它将如下所示:
1 2 3 4 5 | lstEmployee.GroupBy(item => item.FirstName) .Select(grouping => new CountEmployeeName { FirstName = grouping.Key, CountFirstName = grouping.Count() }); |
注意,我建议将