Joining two Lists using Lambdas expression is very simple, lets say we have a inventory of computer products and we have a bunch of purchase orders to process.
So what I am going to do to demonstrate this is to create a class called Product that will have a string property for storing the product’s name and a decimal property for storing the unit price and a property for the product’s id.
public class Product
{
public int Id {
get;
set;
}
public string Name {
get;
set;
}
public decimal UnitPrice {
get;
set;
}
}
Then I create a class called Order that will have a property for the order number as a string, product id as an integer and quantity as a decimal.
public class Order
{
public int ProductId {
get;
set;
}
public string Number {
get;
set;
}
public int Quantity {
get;
set;
}
}
So now I have my classes created I will create a List of products and orders with values. For the Join to work, both lists must have a common reference, and that reference is the Product’s Id.
List<Product> products = new List<Product> {
new Product { Id = 1, Name = "1TB SSD Drive", UnitPrice = 99 },
new Product { Id = 2, Name = "Keyboard", UnitPrice = 39.95M },
new Product { Id = 3, Name = "24 inch Monitor", UnitPrice = 124.99M }
};
As you can see below each order has a referece to a Product Id and a product can 0 to many orders.
List<Order> orders = new List<Order> {
new Order { Number = "A100", ProductId = 2, Quantity = 100 },
new Order { Number = "QZ123", ProductId = 1, Quantity = 10 },
new Order { Number = "1234", ProductId = 2, Quantity = 55 }
};
To join these two list you would use the Lambdas Join expression. Below I query the orders list and join it with the products list by the order’s ProductId and the product’s Id. Then I return each result with a custom object with all the values in it.
var results = orders.Join (products, o => o.ProductId, p => p.Id, ((o, p) => new {
ProductName = p.Name,
UnitPrice = p.UnitPrice,
Number = o.Number,
Quantity = o.Quantity,
TotalCost = p.UnitPrice * o.Quantity
}));
To see the finishing result I write a foreach on the results and output the values to the console.
foreach (var order in results) {
Console.WriteLine ("Order No: {0}, Product: {1}, Qty: {2}, Unit Price: {3}, Total Cost: {4}", order.Number, order.ProductName, order.Quantity, order.UnitPrice, order.TotalCost);
}