List<Employee> empList = new List<Employee>();
empList.AddRange(new Employee[]
{
new Employee {EmpId =1, DeptId=1, Position="Director", Salary=100 },
new Employee {EmpId =2, DeptId=1, Position="Director", Salary = 120},
new Employee {EmpId =3, DeptId=1, Position="Software Engineer", Salary=50 },
new Employee {EmpId =4, DeptId=2, Position="Director", Salary=90 },
new Employee {EmpId =5, DeptId=2, Position="Director", Salary=100 },
new Employee {EmpId =6, DeptId=3, Position="HR Assistant", Salary=40 },
new Employee {EmpId =7, DeptId=3, Position="HR Manager", Salary=70},
new Employee {EmpId =8, DeptId=4, Position="IT Manager", Salary=85 },
new Employee {EmpId =8, DeptId=4, Position="IT Assistant", Salary=40 }
});
/*
* The highest salary from the each dept per position
*/
empList.GroupBy(_ => new { _.DeptId, _.Position })
.Select(_ => new
{
MaximumSalary = _.Max(deptPositionGroup => deptPositionGroup.Salary),
DepartmentId = _.Key.DeptId,
Position = _.Key.Position
}).ToList()
.ForEach(selectedRecords =>
{
Console.WriteLine("{0} {1} {2}", selectedRecords.DepartmentId, selectedRecords.Position, selectedRecords.MaximumSalary);
});
/*Average salary from each dept per position */
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
empList.GroupBy(_ => new { _.DeptId, _.Position })
.Select(_ => new
{
AverageSalary = _.Average(deptPositionGroup => deptPositionGroup.Salary),
DepartmentId = _.Key.DeptId,
Position = _.Key.Position
}).ToList()
.ForEach(selectedRecords =>
{
Console.WriteLine("{0} {1} {2}", selectedRecords.DepartmentId, selectedRecords.Position, selectedRecords.AverageSalary);
});
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
/*Average salary from each dept */
empList.GroupBy(_ => _.DeptId)
.Select(_ => new
{
AverageSalary = _.Average(deptPositionGroup => deptPositionGroup.Salary),
DepartmentId = _.Key,
}).ToList()
.ForEach(selectedRecords =>
{
Console.WriteLine("{0} {1}", selectedRecords.DepartmentId, selectedRecords.AverageSalary);
});
This blog contains information related to .Net programs, Dynamics & many more...
Showing posts with label group by multiple columns linq. Show all posts
Showing posts with label group by multiple columns linq. Show all posts
Wednesday, December 26, 2012
Linq GroupBy with Aggregate functions
Subscribe to:
Posts (Atom)