Blogger news

Blogger templates

Tuesday, February 8, 2011

LINQ- Join Operator


The Join operator performs an inner join of two sequences based on matching keys extracted from the elements. I will explain join with an example,

Consider two entities “Associate” and “Department” as below

class Associate

{

public int AssociateId { get; set; }

public string Name { get; set; }

public int DepartmentId { get; set; }

public int LocationId { get; set; }

}

class Department

{

public int DepartmentId { get; set; }

public string DepartmentName { get; set; }

}

and collection of these two entities,

List<Associate> associates = new List<Associate>

{

new Associate{AssociateId=1,Name="Kiran",DepartmentId=101,LocationId=1},

new Associate{AssociateId=2,Name="Sanjay",DepartmentId=103,LocationId=2},

new Associate{AssociateId=3,Name="Arun",DepartmentId=101,LocationId=4},

new Associate{AssociateId=4,Name="Ajith",DepartmentId=100,LocationId=1},

new Associate{AssociateId=5,Name="Manu",DepartmentId=102,LocationId=5},

};

List<Department> departments = new List<Department>

{

new Department{DepartmentId=100,DepartmentName="Marketing"} ,

new Department{DepartmentId=101,DepartmentName="Human Resource"},

new Department{DepartmentId=102,DepartmentName="Corporate Communication"},

new Department{DepartmentId=103,DepartmentName="Development"}

};

Now I want to join these two collections to get associate details and the department associate belongs to (The same scenario for inner join in sql server). See the query below for the same,

associates.Join(departments, a => a.DepartmentId, d => d.DepartmentId, (a, d) => new { a.AssociateId, a.Name, d.DepartmentName }).ToList()

I will explain “Join” operator parts by parts ,

Please click image to expand,


As in the picture first parameter is IEnumerable <> means expecting a collection to join(in our example associates is outer collection and departments is inner collection). So we can give “departments” as first parameter.

Second parameter is Func <>, means type of “Associate” is input parameter to Func and return a key to compare between two collections (just as compare with two id’s in sql inner join).

Third parameter is Func <>, means type of “Department” is input parameter and return a key to compare with ket returned by second Func above.

Forth parameter is Func<>, means two input parameters of type “Associate” and “Department” and return TResult. In our example we fetch data from both “Associate” and “Department”.

No comments:

Post a Comment