...Technology Simplified

Wednesday, May 23, 2012

How to implement joins in LINQ

No comments :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQPractice
{
class Department
{
public int DeptId { get; set; }
public string DeptName { get; set; }
public string Location { get; set; }
}
class Joins
{
static void Main(string[] args)
{
List employees = new List
{
new Employee{EmpId=100,EmpName="sachin",Salary=15000,DeptName="sales"},
new Employee{EmpId= 101,EmpName="scott",Salary=12000,DeptName="hr"},
new Employee{EmpId=102,EmpName="rahul",Salary=13000,DeptName="it"},
new Employee{EmpId=103,EmpName="ilyas",Salary=13000,DeptName="sales"}
};

List departments = new List
{
new Department {DeptId=1,DeptName="sales",Location="Dublin"},
new Department {DeptId=1,DeptName="hr",Location="Dublin"},
new Department {DeptId=1,DeptName="it",Location="Hyderabad"}
};

Console.WriteLine("Join using LINQ Query");
var joinquery = from emp in employees
join dept in departments
on emp.DeptName equals dept.DeptName
select new { Name = emp.EmpName, Dept = dept.DeptName, Location = dept.Location };
foreach (var item in joinquery)
{
Console.WriteLine("{0,-8}{1,-7}{2,-10}", item.Name, item.Dept, item.Location);
}
Console.ReadLine();
}
}
}

No comments :

Post a Comment