How to Perform Inner Join using LINQ in C# ?

Published on December 25, 2013 by abundantcode

Filed under LINQ

Last modified December 25, 2013

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 4062 times

Are you looking for the syntax on how to perform inner join using LINQ in C# ? . Below is a sample code snippet that demonstrates how to do it.

How to Perform Inner Join using LINQ in C# ?

Assume that the 2 objects that needs to be joined are Employee and EmployeeLeave as shown below.

public class Employee

{

public string Name { get; set; }

public int ID { get; set; }

}
public class EmployeeLeave

{

public int ID { get; set; }

public int EmpID { get; set; }

public int NoOfLeaves { get; set; }

}

The employees and the leaves list contains the following data .

List<Employee> employees = new List<Employee>();

employees.Add(new Employee { ID = 1, Name = "Mark" });

employees.Add(new Employee { ID = 2, Name = "Michael" });

employees.Add(new Employee { ID = 3, Name = "Eddy" });

List<EmployeeLeave> leaves = new List<EmployeeLeave>();

leaves.Add(new EmployeeLeave { ID = 1, EmpID = 1, NoOfLeaves = 10 });

leaves.Add(new EmployeeLeave { ID = 2, EmpID = 2, NoOfLeaves = 4 });

leaves.Add(new EmployeeLeave { ID = 3, EmpID = 1, NoOfLeaves = 7 });

leaves.Add(new EmployeeLeave { ID = 4, EmpID = 3, NoOfLeaves = 1 });

The query to perform the inner join of the objects employees and leaves is as shown below.

var data = (from table1 in employees
                        join table2 in leaves on table1.ID equals table2.EmpID
                        select new { table1.Name, table2.NoOfLeaves }).ToList();

foreach (var item in data)
    Console.WriteLine(item.Name + " has taken " + item.NoOfLeaves);

How to Perform Inner Join using LINQ in C# ?

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

1 Comment

  1. Sourav Das

    Very Good I got many help to your tutorial,so thanks again

    September 14, 2016 - 10:17 am – Reply

Leave a Comment


x

You might be Interested in these Posts

VB.NET and LINQ – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

C# and LINQ – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

VB.NET and LINQ – Filter elements from object collection using where clause

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...