Linq

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Sunday 26 June 2016

Interview Question:- How to use left join in Linq ?

Scenario

  • List of Employee. 
  • List of Departments.
  • Each Employee belongs to Particular department
  • There are some Employees which belongs to some departments which are not there in the department list.
  • Need all the Employees and the department name. Mark 'No Department' for those employees whose departmentId doesn't match with department list.


Code
 using System;    
  using System.Collections.Generic;    
  using System.Linq;    
  using System.Text;    
  namespace GroupJoin    
  {    
  class Program    
  {    
   public static void Main()    
   {    
   List<Employee> objEmployeelist =  new List<Employee>        
    {        
    new Employee{ EmployeeID=1, EmployeeName ="Anurag", DepID=1},    
    new Employee{ EmployeeID=2, EmployeeName ="Abhishek",DepID=2},    
    new Employee{ EmployeeID=4, EmployeeName ="Ayush", DepID=1},    
    new Employee{ EmployeeID=3, EmployeeName ="Rahul", DepID=6}    
    };    
     List<Department> objDepartmentlist = new List<Department>     
    {    
    new Department {DepartmentID=1,DepartmentName="HR"},    
    new Department {DepartmentID=2,DepartmentName="Admin"},    
    new Department {DepartmentID=3,DepartmentName="Lib"},    
    new Department {DepartmentID=4,DepartmentName="Abc"}    
    };    
     var list = (from e in objEmployeelist    
     join d in objDepartmentlist    
     on e.DepID equals d.DepartmentID into ds    
     from d in ds.DefaultIfEmpty()    
     select new { emp = e, dep=(d==null ?"No Department":d.DepartmentName) }).ToList();    
    // loop over here == null ? "(No products)" : p.ProductName    
    foreach (var item in list)    
    {    
    Console.WriteLine(item.emp.EmployeeName + "::" + item.dep);    
    }    
    Console.ReadLine();    
   }    
   }    
   public class Employee    
   {    
   public int EmployeeID;    
   public string EmployeeName;    
   public int DepID;    
   }    
   public class Department    
   {    
   public int DepartmentID;    
   public string DepartmentName;    
   }    
  }    

Output


No comments:

Post a Comment