Here are some common LINQ queries related to joins, demonstrating how to combine data from multiple collections using various join techniques:
Combines elements from two collections based on a matching key.
var orders = new List<Order>
{
new Order { OrderId = 1, CustomerId = 1 },
new Order { OrderId = 2, CustomerId = 2 }
};
var customers = new List<Customer>
{
new Customer { CustomerId = 1, Name = "Rohatash" },
new Customer { CustomerId = 2, Name = "Mohit" }
};
var orderDetails = from order in orders
join customer in customers
on order.CustomerId equals customer.CustomerId
select new
{
OrderId = order.OrderId,
CustomerName = customer.Name
};
// Output: { OrderId = 1, CustomerName = "Rohatash" }, { OrderId = 2, CustomerName = "Mohit" }
Includes all elements from the left collection and matching elements from the right collection. Elements from the left collection without matches in the right collection will still be included.
var employees = new List<Employee>
{
new Employee { EmployeeId = 1, Name = "Rohatash" },
new Employee { EmployeeId = 2, Name = "Mohit" }
};
var projects = new List<Project>
{
new Project { ProjectId = 1, EmployeeId = 1, ProjectName = "Project A" }
};
var employeeProjects = from employee in employees
join project in projects
on employee.EmployeeId equals project.EmployeeId into employeeProjectGroup
from project in employeeProjectGroup.DefaultIfEmpty()
select new
{
EmployeeName = employee.Name,
ProjectName = project?.ProjectName ?? "No Project"
};
// Output: { EmployeeName = "Rohatash", ProjectName = "Project A" }, { EmployeeName = "Mohit", ProjectName = "No Project" }
Groups elements from the second collection by a key, and then joins these groups to the elements of the first collection.
var customers = new List<Customer>
{
new Customer { CustomerId = 1, Name = "Rohatash" },
new Customer { CustomerId = 2, Name = "Mohit" }
};
var orders = new List<Order>
{
new Order { OrderId = 1, CustomerId = 1 },
new Order { OrderId = 2, CustomerId = 1 },
new Order { OrderId = 3, CustomerId = 2 }
};
var customerOrders = from customer in customers
join order in orders
on customer.CustomerId equals order.CustomerId into customerOrderGroup
select new
{
CustomerName = customer.Name,
Orders = customerOrderGroup.ToList()
};
// Output: { CustomerName = "Rohatash", Orders = [{ OrderId = 1 }, { OrderId = 2 }] }, { CustomerName = "Mohit", Orders = [{ OrderId = 3 }] }
Combines every element from the first collection with every element from the second collection.
var colors = new List<string> { "Red", "Green", "Blue" };
var sizes = new List<string> { "Small", "Medium", "Large" };
var colorSizeCombinations = from color in colors
from size in sizes
select new
{
Color = color,
Size = size
};
// Output: { Color = "Red", Size = "Small" }, { Color = "Red", Size = "Medium" }, ...