Getting employees in every department with LINQ LAMBDA
I am trying to combine two employees and a table department using LINQ and trying to get the results in the below image format. Can anyone help how to achieve this.
how to achieve success in the work of employees in each department.
Here is my code
var EmpList = (from d in Department
join e in Employee on d.ID equals e.ID
select new
{
ID = d.ID, Name = d.Name, Location = d.location, Employess =
e.FirstName, e.LastName, e.Gender
});
The above code is incompletely written. I don't understand how to achieve this.
var elist = from d in db.Departments
join e in db.Employees on d.ID equals e.ID
group d by e.DepartmentId into g
select new { Details = g };
+3
source to share
1 answer
Assuming you have a structure like this:
var depts = new[] {
new Dept { ID = 1, Name = "IT", Location = "New York" },
new Dept { ID = 2, Name = "HR", Location = "London" },
new Dept { ID = 3, Name = "Payroll", Location = "Sydney" }
};
var employees = new[] {
new Employee { ID = 1, FirstName = "Mark", DeptID = 1 },
new Employee { ID = 2, FirstName = "Steve", DeptID = 3 },
new Employee { ID = 3, FirstName = "Ben", DeptID = 1 },
new Employee { ID = 4, FirstName = "Philip", DeptID = 2 },
new Employee { ID = 5, FirstName = "Mary", DeptID = 2 },
new Employee { ID = 6, FirstName = "Valarie", DeptID = 3 },
new Employee { ID = 7, FirstName = "John", DeptID = 1 }
};
You can use LINQ Join and GroupBy to get the required data:
var result = depts
.Join(employees.GroupBy(x => x.DeptID), dept => dept.ID, empGroup => empGroup.Key,
(dept, empGroup) => new {
Name = dept.Name,
Location = dept.Location,
Employees = empGroup.ToArray()
});
Or the same thing in SQL type syntax:
var result = from dept in depts
join empGroup in (
from e in employees
group e by e.DeptID into g
select g
) on dept.ID equals empGroup.Key
select new {
Name = dept.Name,
Location = dept.Location,
Employees = empGroup.ToArray()
};
What does it actually do?
- Employees are grouped
DeptID
. - The departments combine with this grouping and result in the collection of anonymous objects in the desired format. You can of course use a strongly typed class.
+1
source to share