How to Perform Inner Join using LINQ in C# ?

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# ?