Write a code snippet for Left outer join using LINQ?

 Posted by Nagasundar_Tn on 10/27/2012 | Category: LINQ Interview questions | Views: 3066 | Points: 40
Answer:

I failed to answer this question in my interview session. So I searched the answer for the question and found in MSDN. After my understanding I just wrote a simple program to understand the left outer join in LINQ.

namespace LeftOuterJoin
{ namespace LeftOuterJoin
{
class Employee
{
public string EmpName { get; set; }
public int EmpAge { get; set; }
public string EmpDeptID { get; set; }
}
class Department
{
public string DeptID { get; set; }
public string DeptName { get; set; }
}
class Program
{
public static void Main(string[] args)
{
Employee objEmp1 = new Employee { EmpName = "Naga", EmpAge = 29, EmpDeptID = "1" };
Employee objEmp2 = new Employee { EmpName = "Sundar", EmpAge = 30, EmpDeptID = "2" };
Employee objEmp3 = new Employee { EmpName = "Siva", EmpAge = 28, EmpDeptID = "3" };
Employee objEmp4 = new Employee { EmpName = "Shankar", EmpAge = 31, EmpDeptID = "4" };
Department objDept1 = new Department { DeptID = "1", DeptName = "IT" };
Department objDept2 = new Department { DeptID = "2", DeptName = "Admin" };
Department objDept3 = new Department { DeptID = "3", DeptName = "Testing" };
Department objDept4 = new Department { DeptID = "4", DeptName = "HR" };
Department objDept5 = new Department { DeptID = "5", DeptName = "Sales" };
//Creating List of Objects
List<Employee> employees = new List<Employee> { objEmp1, objEmp2, objEmp3, objEmp4 };
List<Department> depts = new List<Department> { objDept1, objDept2, objDept3, objDept4, objDept5 };
//Left Side Department Right side Employee
var DeptEmpCollection = from dept in depts
join emp in employees on dept.DeptID equals emp.EmpDeptID into de
from Employees in de.DefaultIfEmpty()
select new { dept.DeptName, EmployeesName = (Employees == null ? "--No Employee--" : Employees.EmpName) };
foreach (var EmpDept in DeptEmpCollection)
{
Console.WriteLine("Dept {0}, EmpName {1}", EmpDept.DeptName, EmpDept.EmployeesName);
}
Console.Read();
}
}
}
}


Source: http://msdn.microsoft.com/en-u | Asked In: In my Last Interview I faced this question | Alert Moderator 

Comments or Responses

Login to post response

More Interview Questions by Nagasundar_Tn