In LINQ, you can use the join
clause to combine two sequences based on a common key. The join
clause works similar to a SQL join statement.
Here's an example of how to apply join
in LINQ:
// create a collection of objects
List<Customer> customers = new List<Customer>
{
new Customer { Id = 1, Name = "Alice", City = "New York" },
new Customer { Id = 2, Name = "Bob", City = "Los Angeles" },
new Customer { Id = 3, Name = "Charlie", City = "Chicago" },
new Customer { Id = 4, Name = "David", City = "New York" },
new Customer { Id = 5, Name = "Eva", City = "Los Angeles" }
};
List<Order> orders = new List<Order>
{
new Order { Id = 1001, CustomerId = 1, Amount = 100 },
new Order { Id = 1002, CustomerId = 2, Amount = 200 },
new Order { Id = 1003, CustomerId = 2, Amount = 300 },
new Order { Id = 1004, CustomerId = 4, Amount = 150 },
new Order { Id = 1005, CustomerId = 5, Amount = 250 }
};
// join customers and orders by customer id
var query = from c in customers
join o in orders on c.Id equals o.CustomerId
select new { CustomerName = c.Name, OrderAmount = o.Amount };
// iterate through the result
foreach (var item in query)
{
Console.WriteLine("Customer: " + item.CustomerName + ", Order Amount: " + item.OrderAmount);
}
In this example, we first create two collections of objects: customers
and orders
, with Customer
and Order
classes respectively. Each Order
has a CustomerId
property that corresponds to the Id
property of a Customer
.
We then use the join
keyword in a LINQ query to join the customers
and orders
collections on the CustomerId
and Id
properties respectively. This creates a new sequence of objects that combines data from both collections.
We then use the select
keyword to create a new anonymous type that contains the Name
property of the Customer
and the Amount
property of the Order
. This creates a new sequence of objects that contains only the data we want to see in the output.
Finally, we iterate through the result using a foreach
loop and print out the CustomerName
and OrderAmount
properties of each object in the sequence.
The output of this code will be:
Customer: Alice, Order Amount: 100
Customer: Bob, Order Amount: 200
Customer: Bob, Order Amount: 300
Customer: David, Order Amount: 150
Customer: Eva, Order Amount: 250
As you can see, the join
operation has combined the data from the customers
and orders
collections based on the CustomerId
and Id
properties, and the output shows the Name
of each Customer
and the Amount
of their Order
.
Comments
Post a Comment