Nagasundar Nagarajan
How we can do left outer join using LINQ? Write a code snippet for that.
By Nagasundar Nagarajan in LINQ on Oct 28 2012
  • Nagasundar Nagarajan
    Oct, 2012 28


    using
    System;
    using
    System.Collections.Generic;
    using
    System.Linq;
    using
    System.Text;
    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();
    }
    }
    }

    • 1
  • Hem ChandraJoshi
    Aug, 2018 17

    from prod in Articles join g1 in MainGroups on prod.MainGroupNo equals g1.MainGroupNo into prodGroup from kat in prodGroup.DefaultIfEmpty() select new { kat.Name, prod.ArticleNo }

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS