Inner Joins by using LINQ

It was demonstrated by taking a simple example. Lets have an e-commerece exmaple whixh conatins the list of products, customers and orders as below.

private List<Products> GetProductsList()
{
var list = new List<Products>();
list.Add(new Products { ProductId = 1, ProductName = “P1” });
list.Add(new Products { ProductId = 2, ProductName = “P2” });
list.Add(new Products { ProductId = 3, ProductName = “P3” });
list.Add(new Products { ProductId = 4, ProductName = “P4” });
return list;
}

private List<Customers> GetCustomersList()
{
var list = new List<Customers>();
list.Add(new Customers { CustomerId = 1, CustomerName = “C1”, Address = “Add” });
list.Add(new Customers { CustomerId = 2, CustomerName = “C2”, Address = “Add” });
list.Add(new Customers { CustomerId = 3, CustomerName = “C3”, Address = “Add” });
list.Add(new Customers { CustomerId = 4, CustomerName = “C4”, Address = “Add” });
return list;
}

private List<Orders> GetOrdersList()
{
var list = new List<Orders>();
list.Add(new Orders { OrderId = 1, CustomerId = 1, ProductId = 1, OrderDate = Convert.ToDateTime(“11/11/2013”) });
list.Add(new Orders { OrderId = 2, CustomerId = 2, ProductId = 2, OrderDate = Convert.ToDateTime(“11/11/2013”) });
list.Add(new Orders { OrderId = 3, CustomerId = 2, ProductId = 3, OrderDate = Convert.ToDateTime(“11/22/2013”) });
return list;
}

Now we will create an inner join on the orders, customers, products to get the data of the customers who purcahased the products.

var list = from productObj in productsList
join ordersObj in ordersList on productObj.ProductId equals ordersObj.ProductId
join customersObj in customersList on ordersObj.CustomerId equals customersObj.CustomerId
select new
{
ProdName = productObj.ProductName,
OrDate = ordersObj.OrderDate,
CustName=customersObj.CustomerName
};
var tempList = list.ToList();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s