GroupJoin operator works on two sequences or collections.It joins the sequences based on a key and returns group for the given key.
Following is the signature of groupjoin operator:
GroupJoin<Outer,Inner, Key, Result>( this IEnumerable<Outer> outer, IEnumerable<Inner> inner, Func<TOuter, Key> outerKeySelector, Func<TInner, Key> innerKeySelector, Func<TOuter, Enumerable<TInner>, TResult> resultSelector )
Following are the type parameters of the GroupJoin() method:
- outer 1st collection
- inner 2nd collection
- outerKeySelector key of 1st collection
- innerKeySelector key of 2nd collection
- resultSelector result.The result of the GroupJoin method is of type IEnumerable<TResult>
The method is not executed until the result enumeration is iterated in a foreach collection.
In the following example we have 2 classes Manager and Employees.Each manager can have multiple employees reporting to him.We are grouping the Manager and his reportees based on the ManagerId key.
Class Manager
public class Manager { public int ManagerId { get; set; } public string Name { get; set; } }
Class Employees
public class Employees { public int ManagerId { get; set; } public int Id { get; set; } public string Name { get; set; } }
Using outerJoin to group the 2 collections based on Manager Id:
class Program { static void Main(string[] args) { IList<Manager> managerlist = new List<Manager>() { new Manager() {ManagerId=1,Name="Mnager1" }, new Manager() {ManagerId=2,Name="Mnager2" } }; IList<Employees> employeelist = new List<Employees>() { new Employees(){ Id = 1, Name="Standard 1",ManagerId=1}, new Employees(){ Id = 2, Name="Standard 2",ManagerId=1} }; var groupJoin = managerlist.GroupJoin(employeelist, //inner sequence manager => manager.ManagerId, //outerKey employee => employee.ManagerId, //innerKey (manager, employeeGroup) => new // result { employees = employeeGroup, manager = manager.Name }); foreach (var item in groupJoin) { Console.WriteLine(item.manager); foreach (var emp in item.employees) Console.WriteLine(emp.Name); } Console.ReadLine(); } }
Leave a Reply