Part 21 - Group Join in LINQ

The following are the different types of joins in LINQGroup Join - We will discuss in this videoInner Join - Discussed in Part 22Left Outer JoinCross Join

In this video, we will discuss Group Join. Group Join produces hierarchical data structures. Each element from the first collection is paired with a set of correlated elements from the second collection.

Let us understand Group Join with an example. Consider the following Department and Employee classes. A Department may have ZERO or MORE employees.

publicclassDepartment

{

publicint ID
{ get; set;
}

publicstring Name
{ get; set;
}

publicstaticList<Department> GetAllDepartments()

{

returnnewList<Department>()

{

newDepartment { ID = 1, Name = "IT"},

newDepartment { ID = 2, Name = "HR"},

newDepartment { ID = 3, Name = "Payroll"},

};

}

}

publicclassEmployee

{

publicint ID
{ get; set;
}

publicstring Name
{ get; set;
}

publicint DepartmentID
{ get; set;
}

publicstaticList<Employee> GetAllEmployees()

{

returnnewList<Employee>()

{

newEmployee { ID = 1, Name = "Mark", DepartmentID = 1
},

newEmployee { ID = 2, Name = "Steve", DepartmentID =
2 },

newEmployee { ID = 3, Name = "Ben", DepartmentID = 1
},

newEmployee { ID = 4, Name = "Philip", DepartmentID =
1 },

newEmployee { ID = 5, Name = "Mary", DepartmentID = 2
},

newEmployee { ID = 6, Name = "Valarie", DepartmentID =
2 },

newEmployee { ID = 7, Name = "John", DepartmentID = 1
},

newEmployee { ID = 8, Name = "Pam", DepartmentID = 1
},

newEmployee { ID = 9, Name = "Stacey", DepartmentID =
2 },

newEmployee { ID = 10, Name = "Andy", DepartmentID = 1}

};

}

}

Example 1: Group employees by Department.

var employeesByDepartment = Department.GetAllDepartments()

.GroupJoin(Employee.GetAllEmployees(),

d => d.ID,

e => e.DepartmentID,

(department, employees) =>
new

{

Department = department,

Employees = employees

});

foreach (var department in employeesByDepartment)

{

Console.WriteLine(department.Department.Name);

foreach (var employee
in department.Employees)

{

Console.WriteLine("
" + employee.Name);

}

Console.WriteLine();

}

Output:

Example 2: Rewrite Example 1 using SQL like syntax.

var employeesByDepartment = from d inDepartment.GetAllDepartments()

join e inEmployee.GetAllEmployees()

on d.ID equals e.DepartmentID into eGroup

selectnew

{

Department = d,

Employees = eGroup

};

Please note: Group Join uses the join operator and the into keyword to group the results of the join.