LINQ Group By and select collection

前端 未结 3 1091
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 09:58

I have this structure

Customer
 - has many Orders
  - has many OrderItems

I want to generate a list of CustomerItems via LINQ give

相关标签:
3条回答
  • 2021-01-30 10:36

    you can achive it with group join

    var result = (from c in Customers
              join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
              Select new { customer = c, orderItems = g});
    

    c is Customer and g is the customers order items.

    0 讨论(0)
  • 2021-01-30 10:40

    I think you want:

    items.GroupBy(item => item.Order.Customer)
         .Select(group => new { Customer = group.Key, Items = group.ToList() })
         .ToList() 
    

    If you want to continue use the overload of GroupBy you are currently using, you can do:

    items.GroupBy(item => item.Order.Customer, 
                  (key, group) =>  new { Customer = key, Items = group.ToList() })
         .ToList() 
    

    ...but I personally find that less clear.

    0 讨论(0)
  • 2021-01-30 10:48

    you may also like this

    var Grp = Model.GroupBy(item => item.Order.Customer)
          .Select(group => new 
            { 
                 Customer = Model.First().Customer, 
                 CustomerId= group.Key,  
                 Orders= group.ToList() 
           })
          .ToList();
    
    0 讨论(0)
提交回复
热议问题