关于c#:我想计算通用列表中特定组的出现次数

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
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)

我想根据员工列表的给定数据绑定上面输出的CountEmployeeName类的通用列表。


使用linq group by,然后在select项目中使用第二种类型:

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()
                   });

注意,我建议将CountFirstName改为int而不是string