Tuesday, 31 October 2017

INNER JOIN Example Using Lambda Expression In C# Asp.Net


Introduction
In this article we will learn how to use join using Lambda Expression in C#. Join example with Lambda Expression using LIST collection. 

Previous Updates
In previous articles we have learnt  Maintain state of dynamic added userConrol in asp.net using c#.Arrange Distinct Elements Of A List In Ascending Order Using LINQ 

Description:
Here i am using the List collection to store the temporary/static data. In your case may be it will the database data. 
Below is My two class just like two tables Student and Department.
static void Main(string[] args)
{
    List<Emp> liEmp = new List<Emp>();
    liEmp.Add(new Emp { EmpID = 1, EmpName = "JP" });
    liEmp.Add(new Emp { EmpID = 2, EmpName = "GurujiPoint" });
    liEmp.Add(new Emp { EmpID = 3, EmpName = "PointGuruji" });
    liEmp.Add(new Emp { EmpID = 6, EmpName = "DE" });
    liEmp.Add(new Emp { EmpID = 8, EmpName = "EF" });

    List<Dep> lstDep = new List<Dep>();
    lstDep.Add(new Dep { DepID = 1, Department = ".Net", EmpID = 1 });
    lstDep.Add(new Dep { DepID = 2, Department = "PHP", EmpID = 2 });
    lstDep.Add(new Dep { DepID = 3, Department = "ASP", EmpID = 3 });
    lstDep.Add(new Dep { DepID = 4, Department = "Android", EmpID = 4 });
    lstDep.Add(new Dep { DepID = 5, Department = "GD", EmpID = 5 });
    lstDep.Add(new Dep { DepID = 6, Department = "UI", EmpID = 6 });

//INNER JOIN Using Lambda Expression
var lamdaData = 
liEmp.Join(lstDep, emp => emp.EmpID, dep => dep.EmpID, (emp, dep) => new
{
    emp.EmpID,
    emp.EmpName,
    dep.Department
});
foreach (var data in lamdaData)
    {
        Console.WriteLine("EmpId = " + data.EmpID
                         + ",Emp Name = " + data.EmpName +
                        ",Department = " + data.Department);
    }
    Console.ReadLine();
}

Output:
 Removing duplicate records from SQL Table

EmpId = 1,Emp Name = JP,Department = .Net
EmpId = 2,Emp Name = GurujiPoint,Department = PHP
EmpId = 3,Emp Name = PointGuruji,Department = ASP
EmpId = 6,Emp Name = DE,Department = UI



No comments:

Post a Comment