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 EmployeeOur aim is to find those employee from each department who earns the most. Here I am manually creating some employee as shown below
{
public string Name { get; set; }
public string Department { get; set; }
public int Salary { get; set; }
}
List<Employee> employeeList = new List<Employee>();Now check the LINQ statement for finding the most earning employees for each department.
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 });
var employees = from e in employeeListFor demonstrating lets print the values to screen
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
};
foreach (var emp in employees)Hope this helps.
{
Console.WriteLine("In Department {0}, Employee {1} has the highest salary {2}",
emp.Department, emp.Name, emp.Salary);
}
1 comment:
Thanks! Worked like a charm!
Post a Comment