Thursday, August 28, 2014

Inner Join Example in LINQ and C#

Inner Join Example in LINQ and C#
Let see an example of using the Join method in LINQ and C#. The Join method performs an inner equijoin on two sequences, correlating the elements of these sequences based on matching keys. It is called equijoin, since we are testing for equality using the equals operator.
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" } };


        //At first glance, LINQ appears to only offer a join operator with an 'inner join' behavior. That is, when joining a sequence of address with a sequence of person, we will only see those person that have one or more addresses.

        var query = from ppl in people
                    join adr in address on ppl.EmpId equals adr.EmpId
                    select new { ppl.FirstName, ppl.LastName, CityName = adr.CityName, StateName = adr.StateName };//Inner Join
        //using Labda expression
        var queryLambda = people.Join(address, r => r.EmpId, p => p.EmpId, (r, p) => new { r.FirstName, r.LastName, p.CityName,p.StateName });

No comments:

Post a Comment

http://blogsiteslist.com