Tuesday, 31 October 2017

INNER JOIN Example Using LINQ In C# Asp.Net


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


Previous Updates
In previous articles we have learnt  Maintain state of dynamic added userConrol in asp.net using c#. Insert Only Numeric values in Asp Textbox using Regex

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.
        class Emp
        {
            public int EmpID { getset; }
            public string EmpName { getset; }
        }
        class Dep
        {
            public int DepID { getset; }
            public string Department { getset; }
            public int EmpID { getset; }
        }
Below i fill the dummy data into List , it just like your SQL table data and now i want to retrieve only those employee records who are common with Departments.
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 = "AB" });
    liEmp.Add(new Emp { EmpID = 3, EmpName = "CD" });
    liEmp.Add(new Emp { EmpID = 6, EmpName = "EF" });
    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 });

    //InnerJoin Using LINQ 
    var finalData = from emp in liEmp
                    join dep in lstDep
         on emp.EmpID equals dep.EmpID
                    select new
                    {
                        emp.EmpID,
                        emp.EmpName,
                        dep.Department
                    };
    foreach (var data in finalData)
    {
        Console.WriteLine("EmpId = " + data.EmpID
                         + ",Emp Name = " + data.EmpName +
                        ",Department = " + data.Department);
    }
    Console.ReadLine();
}
Output:
EmpId = 1,Emp Name = JP,Department = .Net
EmpId = 2,Emp Name = AB,Department = PHP
EmpId = 3,Emp Name = CD,Department = ASP
EmpId = 6,Emp Name = EF,Department = UI

1 comment: