I have two tables Customers and Orders. I want a LINQ query to fetch list of all the orders placed by all the customers organized first by month and then by year. If there i
Something like this. You can do it using LINQ Predicates
var res = Customers.Join(Orders, x => x.customer_id, y => y.customer_id, (x, y) => x).ToList();
This is what you can do:
var res = from cust in db.Customers
join ord in db.Orders
on cust.customer_id equals ord.customer_id into g
from d in g.DefaultIfEmpty()
orderby d.OrderDate.Year, d.OrderDate.Month
select new {
name=cust.name,
oId = d.order_id.ToString() ?? "No Orders"
};
I finally got the right answer which exactly the result as expected. I have put it below. I have used two LINQ queries to arrive at the result though. The first one gives the result, but the final result needs to be displayed with names of customer and their order totals, hence it is partial result. The second LINQ query further refines the 'partialResult' and gives the result as expected.
var partialResult = (from c in db.Customers
join o in db.Orders
on c.customer_id equals o.customer_id
select new
{c.name,
o.order_total,
o.order_date }).OrderBy(m => m.order_date.Month).ThenBy(y => y.order_date.Year);
var finalResult = from c in db.Customers
orderby c.name
select new
{
name = c.name,
list = (from r in partialResult where c.name == r.name select r.order_total).ToList()
};
foreach (var item in finalResult)
{
Console.WriteLine(item.name);
if (item.list.Count == 0)
{
Console.WriteLine("No orders");
}
else
{
foreach (var i in item.list)
{
Console.WriteLine(i);
}
}
}