Thursday, August 28, 2014

Left & Right Outer Join Example in LINQ using Lambda Expression

Left & Right Outer Join Example in LINQ using Lambda Expression

Combines two collections into a single hierarchical collection. The join operation is based on matching keys.This is called group join so lambda expression we can use the group join to achieve the result
Suppose we have two classes’ person and Address
public class Person
{
    public int EmpId { getset; }
    public string FirstName { getset; }
    public string LastName { getset; }
}

public class Address
{
    public int AddressId { getset; }
    public int EmpId { getset; }
    public string CityName { getset; }
    public string StateName { getset; }

}
//insert the data person and address classsed
         List<Person> people = new List<Person> {
            new Person{ EmpId = 1, FirstName = "Abc", LastName = "xyz0" },
            new Person{ EmpId = 2, FirstName = "Abc01", LastName = "xyz1" },
            new Person{ EmpId = 3, FirstName = "Abc02", LastName = "xyz2" },
            new Person{ EmpId = 4,FirstName="Abc03", LastName="xyz3" },
            new Person{ EmpId = 5,FirstName="Abc04", LastName="xyz4" },
            new Person{ EmpId = 6,FirstName="Abc05", LastName="xyz5" } };
        //  List pets = new List { barley, boots, whiskers, bluemoon, daisy };

        List<Address> address = new List<Address> {
            new Address{ AddressId = 1,EmpId=1, CityName = "Delhi", StateName = "Delhi" },
            new Address{ AddressId = 2,EmpId=1 , CityName= "Chandigarh", StateName ="Punjab" },
            new Address{ AddressId = 3, EmpId=1, CityName= "Shimla", StateName = "himachal"},
            new Address{ AddressId = 4,EmpId=2 ,CityName ="kanpur", StateName="Up" },
            new Address{ AddressId = 5,EmpId=4,CityName="other1", StateName="xyz4" },

            new Address{ AddressId = 6, EmpId=2, CityName="others", StateName="xyz5" } };

 



var Query=people.GroupJoin
(address,p=>p.EmpId,a=>a.EmpId,(p,a)=>new{people=p,address=a}).Select(o=>o);

No comments:

Post a Comment

http://blogsiteslist.com