Linq Multiple Joins和Group By

时间:2013-12-13 21:58:03

标签: c# asp.net linq

所以我甚至不确定我所做的事情是否可行,但我基本上试图采用4个不同的列表,将它们加入到1个对象中。

唯一的问题是,orderLineItems将是一个集合,我无法找到将其纳入相应列表项的最佳方法。我知道我可能需要做一个小组,但是当我做Select时,小组似乎打破了分配

要澄清一点:挑战是获取LineItems - 如果我没有分配行项目并从查询中删除任何lineitem引用,则数据会正确填充,但是,因为lineitems是一个我无法弄清楚在Select中分配它们的正确方法 - 希望有意义..

var ordersa = (from order1 in orderList
  join person in customerAccountPeople
       on order1.CustomerAccountPersonId equals person.CustomerAccountPersonId
  join subject in subjectList
       on order1.SubjectId equals subject.SubjectId
  from orderLineItem in orderLineItemList
  join order in orderList
       on orderLineItem.OrderId equals order.OrderId
  group orderLineItem by orderLineItem.OrderId into orderLineItems
  select new OrderList()
  {
      Customer = person,
      Subject = subject,
      Order = order1,
      LineItems = orderLineItems
  }).ToList();

2 个答案:

答案 0 :(得分:2)

在您当前的解决方案中,您基本上是按照订单,主题和人员加入每个订单项,然后按订单ID对结果列表进行分组。这不是您想要的:您希望订单,主题和人员以及订单项列表。

您应该事先对订单项进行分组。由于您澄清了所有内容都在内存中,因此您可以按订单ID使用ILookup个订单行项目:

 // GroupBy works just as well
 var orderLineItemsByOrderId = orderLineItemList.ToLookup(ol => ol.OrderId);
 var ordersa = (
     from order1 in orderList
     join person in customerAccountPeople
     on order1.CustomerAccountPersonId equals person.CustomerAccountPersonId
     join subject in subjectList
     on order1.SubjectId equals subject.SubjectId
     let orderLineItems = orderLineItemsByOrderId[order1.OrderId]
     select new 
     {
         Customer = person,
         Subject = subject,
         Order = order1,
         LineItems = orderLineItems
     }).ToList();

答案 1 :(得分:0)

    var ordersa = (from order1 in orderList
                   join person in customerAccountPeople
                        on order1.CustomerAccountPersonId equals person.CustomerAccountPersonId
                   join subject in subjectList
                        on order1.SubjectId equals subject.SubjectId
                   select new OrderList()
                   {
                       Customer = person,
                       Subject = subject,
                       Order = order1,
                       LineItems =    ( from orderLineItem in orderLineItemList
                                           join order in orderList
                                                on orderLineItem.OrderId equals order1.OrderId
                                           group orderLineItem by orderLineItem.OrderId into orderLineItems )
                   }).ToList();