linq query join in csharp

Here's an example of how to perform a join using LINQ query syntax in C#:

Suppose we have two collections of objects: orders and customers. Each order object has a CustomerId property, which is the same as the Id property of a corresponding customer object.

main.cs
// Define the collections
List<Customer> customers = new List<Customer>();
List<Order> orders = new List<Order>();

// Perform the join
var query = from order in orders
            join customer in customers on order.CustomerId equals customer.Id
            select new { OrderId = order.Id, CustomerName = customer.Name };
324 chars
9 lines

In the above example, we perform a join on the CustomerId and Id properties of the Order and Customer objects, respectively. We then select a new anonymous object with properties OrderId and CustomerName.

Note that join is a keyword in LINQ query syntax that performs an inner join. There are also other types of joins available, such as left join, right join, and full outer join. Additionally, there is an equivalent method syntax for performing joins using LINQ, which may be more familiar to developers coming from languages like SQL.

related categories

gistlibby LogSnag