LINQGroupBy 并选择集合

我有这种结构

Customer
- has many Orders
- has many OrderItems

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

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

它是顾客从商品子集中订购的所有商品的分组

我怎样才能使用 LINQ 回溯跟踪通过订单和分组的客户生成这个对象?

到目前为止,我还在

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

但这显然不是一个名单。我想我需要一个 SelectMany 在那里的地方,但可以做一些指针。

290411 次浏览

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.

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.

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