Join two tables using LINQ Query and order based two parameters

前端 未结 3 924
深忆病人
深忆病人 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:54

    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();
    
    0 讨论(0)
  • 2021-01-18 04:58

    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" 
              };
    
    0 讨论(0)
  • 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);
                        }
                    }
                }
    
    0 讨论(0)
提交回复
热议问题