C# Keywords Tutorial Part 58: on

C# Keywords Tutorial Part 58: on

C# is a versatile and powerful programming language that provides a rich set of features for manipulating data. One of the most useful features of C# is LINQ (Language-Integrated Query), which provides a simple and expressive way to query data from different data sources. In this blog post, we will explore how to use the “on” keyword in LINQ queries.

Using the “on” keyword in LINQ

The “on” keyword in LINQ is used to specify the join condition between two data sources. A join operation combines two data sources into a single result set based on a common key. The “on” keyword is used to specify the key that is used to match the elements from the two data sources.

Here’s an example of how to use the “on” keyword in a LINQ query:

var result = from person in persons
             join address in addresses
             on person.AddressId equals address.Id
             select new { person.Name, address.City };

In this example, we have two data sources: a list of persons and a list of addresses. We want to join these two data sources based on a common key: the person’s address ID and the address ID. We use the “on” keyword to specify the join condition: person.AddressId equals address.Id.

The result of the query is a new anonymous type that contains the person’s name and the city where they live.

Using multiple keys with the “on” keyword

In some cases, you may need to join two data sources based on multiple keys. For example, suppose you have two data sources: a list of orders and a list of products. You want to join these two data sources based on two keys: the order’s product ID and the product’s category ID. Here’s how you can use the “on” keyword to specify multiple keys in a LINQ query:

var result = from order in orders
             join product in products
             on new { order.ProductId, order.CategoryId } equals new { product.Id, product.CategoryId }
             select new { order.OrderNumber, product.Name, product.Category };

In this example, we use the “on” keyword to specify two keys: order.ProductId and order.CategoryId, and product.Id and product.CategoryId. We use an anonymous type to combine these two keys and compare them in the join condition.

The result of the query is a new anonymous type that contains the order number, product name, and product category.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *