C# 3.0 : Joining two in-memory collection through LINQ

C# 3.0 : Joining two in-memory collection through LINQ

  • Comments 4

LINQ allows us to join different collection source provided we are mapping with two properties with the same type. It is easy, it is quick and it is concise.

 

 

//Create Employee Class

class Employee

{

    public int ID { get; set; }

    public string Name { get; set; }

    public string ManagerId { get; set; }

}

 

//Create Manager Class

class Manager

{

    public string Id { get; set; }

    public string Name { get; set; }

}

 

class Program

{

    //Create the List<Manager>

    static List<Manager> GetManagers()

    {

        return new List<Manager>

        {

            new Manager(){Id = "M1", Name = "Manager 1"},

            new Manager(){Id = "M2", Name = "Manager 2"}

        };

    }

 

    //Create the List<Employee>

    static List<Employee> GetEmployees()

    {

        return new List<Employee>

        {

            new Employee(){ID = 1, Name = "A", ManagerId = "M1"},

            new Employee(){ID = 2, Name = "B", ManagerId = "M1"},

            new Employee(){ID = 3, Name = "C", ManagerId = "M1"},

            new Employee(){ID = 4, Name = "D", ManagerId = "M1"},

            new Employee(){ID = 5, Name = "E", ManagerId = "M2"},

            new Employee(){ID = 6, Name = "F", ManagerId = "M2"},

            new Employee(){ID = 7, Name = "G", ManagerId = "M2"},

            new Employee(){ID = 9, Name = "H", ManagerId = "M5"}

        };

    }

 

    static void Main(string[] args)

    {

        /*Doing join between two sources

         *The record will be retieved only the mathched data

             * Output will give values from both the collection

             */

            var query = from e in GetEmployees()

                        join m in GetManagers() on e.ManagerId equals m.Id

                        select new

                        {

                            EmployeeId = e.ID,

                            EmployeeName = e.Name,

                            Manager = m.Name

                        };

 

            foreach (var o in query)

            {

                Console.WriteLine("{0}-{1} [{2}]",

                    o.EmployeeId,

                    o.EmployeeName,

                    o.Manager);

            }           

        }       

    }

 

Namoskar!!!

Leave a Comment
  • Please add 8 and 2 and type the answer here:
  • Post
  • LINQ allows us to join different collection source provided we are mapping with two properties with the

  • Very good my brother.

    Tanks.

  • Very simple and easy to unerstand, This solved my linq joining tables problem

    Thanks

  • Thanks buddy you made my day.

    -Regards

    NG

Page 1 of 1 (4 items)