This blog is moved to
http://amalhashim.wordpress.com

Thursday, November 12, 2009

Highest value in each group using LINQ

First of all, let me thank Suportim for explaining how to achieve this. For demonstrating I have created an employee class as shown below.

public class Employee
{
public string Name { get; set; }
public string Department { get; set; }
public int Salary { get; set; }
}
Our aim is to find those employee from each department who earns the most. Here I am manually creating some employee as shown below
List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee() { Name = "John", Department = "Web", Salary = 1000 });
employeeList.Add(new Employee() { Name = "Frank", Department = "Web", Salary = 2000 });
employeeList.Add(new Employee() { Name = "Loyd", Department = "Web", Salary = 3000 });
employeeList.Add(new Employee() { Name = "Peter", Department = "IT", Salary = 1500 });
employeeList.Add(new Employee() { Name = "Tevez", Department = "IT", Salary = 2500 });
employeeList.Add(new Employee() { Name = "James", Department = "IT", Salary = 3500 });
employeeList.Add(new Employee() { Name = "Peter", Department = "Finance", Salary = 500 });
employeeList.Add(new Employee() { Name = "Tevez", Department = "Finance", Salary = 1500 });
employeeList.Add(new Employee() { Name = "Cameron", Department = "Finance", Salary = 3250 });
Now check the LINQ statement for finding the most earning employees for each department.
var employees = from e in employeeList
group e by e.Department into egrp
let max = egrp.Max(sal => sal.Salary)
select new
{
Department = egrp.Key,
Name = egrp.First(val=>val.Salary == max).Name,
Salary = egrp.First(val=>val.Salary == max).Salary
};
For demonstrating lets print the values to screen
foreach (var emp in employees)
{
Console.WriteLine("In Department {0}, Employee {1} has the highest salary {2}",
emp.Department, emp.Name, emp.Salary);
}
Hope this helps.

1 comment:

Nick Olsen said...

Thanks! Worked like a charm!