Join two tables using LINQ Query and order based two parameters

前端 未结 3 926
深忆病人
深忆病人 2021-01-18 04:15

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

3条回答
  •  有刺的猬
    2021-01-18 04:59

    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);
                        }
                    }
                }
    

提交回复
热议问题