LINQ Grouping two classes data:
The following code shows how to group two classes together and apply query on them to get your required data. See the code below.
Code
// Creating orderList and adding Orders objects in the list
List<Orders> orderList = new List<Orders> {
new Orders
{
OrderID = 1,
ItemName = "Biscuit",
CustomerID = 10,
Cost = 49.9
},
new Orders
{
OrderID = 2,
ItemName = "Chips",
CustomerID = 15,
Cost = 18.50
},
new Orders
{
OrderID = 3,
ItemName = "Deodorant",
CustomerID = 20,
Cost = 99.9
},
new Orders
{
OrderID = 4,
ItemName = "Shaving Gel",
CustomerID = 20,
Cost = 170
},
new Orders
{
OrderID = 5,
ItemName = "Lipstick",
CustomerID = 25,
Cost = 70
}
// Creating customerList and adding Customer objects in the list
List<Customer> customerList = new List<Customer>
{
new Customer {
CustomerID = 10,
Name = "Osama",
Email = "osamammursleen@gmail.com"
},
new Customer {
CustomerID = 15,
Name = "Saad",
Email = "saadbinsaulat@gmail.com"
},
new Customer {
CustomerID = 20,
Name = "Bilal",
Email = "bilalkhan_leo@hotmail.com"
},
new Customer {
CustomerID = 25,
Name = "Maryam",
Email = "maryamali@hotmail.com"
},
new Customer {
CustomerID = 30,
Name = "Zainab Sheikh",
Email = "zainabsheikh@yahoo.com"
}
};
// Query : Getting Data From orderList And Showing Which Cutomer spent money on orders
var ordersByCustomer =
from Orders o in orderList
group o by o.CustomerID;
foreach (var cust in ordersByCustomer)
{
Console.WriteLine("Customer ID : " + cust.Key.ToString() + " , ordered " + cust.Count().ToString() + " items");
foreach (var item in cust)
Console.WriteLine("Order ID : " + item.OrderID.ToString() + " , Item Name : " + item.ItemName + " , Cost : " + item.Cost.ToString() + " RS");
}
Output:
Customer ID : 10 , ordered 1 items
OrderID : 1 , Item Name : Biscuit , Cost : 49.9 RS
Customer ID : 15 , ordered 1 items
OrderID : 2 , Item Name : Chips , Cost : 18.5 RS
Customer ID : 20 , ordered 2 items
OrderID : 3 , Item Name : Deodorant , Cost : 99.9 RS
OrderID : 4 , Item Name : Shaving Gel , Cost : 170 RS
Customer ID : 25 , ordered 1 items
OrderID : 5 , Item Name : Lipstick , Cost : 70 RS
0 comments:
Post a Comment