Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get aggregated values from a collection using values from the same collection as predicate

Tags:

c#

I have a list containing Employee Model Objects.

public List<EmployeeModel> EmployeeData()
{
    return new List<EmployeeModel>()
    {
         new EmployeeModel(){ EmpID = 1, EmpSSN = 11, LName = "Motor", FName = "Mouse" },
         new EmployeeModel(){ EmpID = 2, EmpSSN = 11, LName = "Motor", FName = "Mouse" },
         new EmployeeModel(){ EmpID = 3, EmpSSN = 11, LName = "Motor", FName = "Mouse" },

         new EmployeeModel(){ EmpID = 1, EmpSSN = 12, LName = "Cat", FName = "Auto" },
         new EmployeeModel(){ EmpID = 2, EmpSSN = 12, LName = "Cat", FName = "Auto" },
    };
}

I need to list each employee and their total EmpSSN occurrence so that the output will look like this:

Last Name: Mouse. Total EmpSSN: 3
Last Name: Cat. Total EmpSSN: 2

I can do something like this to get the names:

var name = data.EmployeeData().Select(x => x.LastName).Distinct();

However, I am not certain how to get the EmpSSN Count without writing extraneous code or using the same list twice, given I will not know the data in the list or have arguments to pass.

like image 796
Altitude Avatar asked Nov 20 '25 08:11

Altitude


1 Answers

Rather than using Distinct, use GroupBy:

var name = data.EmployeeData()
    .GroupBy(x => x.LastName)
    .Select(g => new {
        LastName = g.Key
    ,   TotalEmpSsn = g.Count()
    });

Since LastName is used as the group's key, Select gets groups combining records with identical last name. If you are looking to coult items within the group where a specific predicate would be true (e.g. EmpSsn above a certain number, etc.) you can supply that predicate to the Count() method.

like image 56
Sergey Kalinichenko Avatar answered Nov 21 '25 22:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!