-1

I have two class .

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

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)

I want to bind Generic List of CountEmployeeName class like above output as per given data for Employee List .

Ronak Patel
  • 630
  • 4
  • 15

1 Answers1

3

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

Note that I'd recommend changing the CountFirstName to an int rather than string

Gilad Green
  • 36,708
  • 7
  • 61
  • 95