Monday, January 2, 2012

LINQ : Joins


Here we are going to write Linq queries which will perform Left Join, Left Outer Join, and Cross Join. We have 2 tables Employess and Department. Employees has 5 rows and Department has 4 rows as shown below.

  1. Join : Here is a query which will join Employees and Department and show the result.

Query :
var joins = from em in Employees
join d in Departments on em.DeptId equals d.DeptId
select new {Name = em.EmpName, Department = d.DeptName};

 Output :

2. Left Outer Join : Here is a query which will Left outer join Employess with Department and show the result.
Query :
var leftouterjoins = from em in Employees
                     join d in Departments on em.DeptId equals d.DeptId
                      into empd
                     from ed in empd.DefaultIfEmpty()
                     select new {Name = em.EmpName, 
                          Department = ed == null ? string.Empty:  ed.DeptName};
Output:


3.
 Cross Join : Here is a query which will cross join Employee table with Department and show the result.
Query:
  var crossjoins = from em in Employees
                   from d in Departments
                   select new {Name = em.EmpName, Department = d.DeptName};

Output:



No comments:

Post a Comment