C# LINQ 分组依据和选择集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10637760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:36:50  来源:igfitidea点击:

LINQ Group By and select collection

c#linqgroup-by

提问by jenson-button-event

I have this structure

我有这个结构

Customer
 - has many Orders
  - has many OrderItems

I want to generate a list of CustomerItemsvia LINQ given a subset of OrderItems:

我想CustomerItems通过给定以下子集的 LINQ生成一个列表OrderItems

List of new { Customer, List<OrderItem> Items }

which is a grouping of all the items a Customer has ordered from the subset of items

这是客户从项目子集中订购的所有项目的分组

How can i use LINQ to back track through the order and group by Customer to generate this object?

如何使用 LINQ 回溯订单和客户分组以生成此对象?

so far I'm on something like

到目前为止,我正在做类似的事情

items
 .GroupBy(i => i, i => i.Order.Customer, (i, customer) => new {customer, i})

But thats obviously not a List. I'm guessing I need a SelectMany in there somewhere, but could do with some pointers.

但这显然不是一个列表。我猜我在某个地方需要一个 SelectMany,但可以使用一些指针。

采纳答案by Ani

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 GroupByyou are currently using, you can do:

如果您想继续使用GroupBy您当前正在使用的重载,您可以执行以下操作:

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

...but I personally find that less clear.

...但我个人觉得不太清楚。

回答by cimey

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.

c 是客户,g 是客户订购的商品。

回答by caras

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