Translate

Thursday, April 26, 2012

Linq join two generic lists (linq join two tables)


What are we trying to achieve?

Suppose you want to join  Employees Table  and  Players Table  on first name.



Employees Table:
FirstName
Employer
A
TJX
B
G4s
C
Google

Players Table:
FirstName
Club
A
Manchester United
D
Chelsea
C
Arsenal


Table that joins the above two tables on first name.
FirstName
Employer
Club
A
TJX
Manchester United
C
Google
Arsenal




How do we do it?


The way you would do this in C# is by creating two Lists and then combine them using join.  This is how the code that does the join looks like


Join:

var playerEmployee = from employee in empList
                    join player in soclist
                    on employee.FirstName equals player.FirstName
                    select new { employee, player };

foreach (var x in playerEmployee)
{

}


Left Join:

SoccerPlayer dummyPlayer = new SoccerPlayer();

var playerEmployeeLeftJoin = from employee in empList
join player in soclist
on employee.FirstName equals player.FirstName into playerAlias
from player in playerAlias.DefaultIfEmpty()
select new { employee, player = (player == null ? dummyPlayer : player) };

foreach (var x in playerEmployeeLeftJoin)
{

}


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator