简体   繁体   English

如何使用Linq从父列表中选择和分组复杂的子对象

[英]How to use Linq to select and group complex child object from a parents list

How to use Linq to select and group complex child object from a parents list. 如何使用Linq从父列表中选择和分组复杂的子对象。

I have an OrderList each of order object has a OrderProductVariantList (OrderLineList), and each of OrderProductVariant object has ProductVariant, and then the ProductVariant object will have a Product object which contains product information. 我有一个OrderList,每个订单对象都有一个OrderProductVariantList (OrderLineList),每个OrderProductVariant对象都有ProductVariant,然后ProductVariant对象将有一个Product对象,其中包含产品信息。

My goal is to select and group the most popular products from the order list. 我的目标是从订单列表中选择和分组最受欢迎的产品。

Can anyone help me with this? 谁能帮我这个?

Many thanks. 非常感谢。

Your description is hard to follow, but I think you just want to get out the Products and rank them by the number of times they occur. 您的描述很难理解,但我认为您只想获取产品并按发生次数对其进行排名。 SelectMany will be helpful for this. SelectMany将对此有所帮助。

 var query = orderList.SelectMany( o => o.OrderLineList )
                        // results in IEnumerable<OrderProductVariant>
                      .Select( opv => opv.ProductVariant )
                      .Select( pv => p.Product )
                      .GroupBy( p => p )
                      .Select( g => new {
                                    Product = g.Key,
                                    Count = g.Count()
                       });

A query is not a result. 查询不是结果。 To view the result you can iterate over the query object: 要查看结果,您可以遍历query对象:

foreach (var result in query) {
    Console.WriteLine(result);
} 

As to why query wasn't available in the watch window, I can only imagine that it either wasn't in scope yet, or it had already gone out of scope. 至于为什么查询在观察窗口中不可用,我只能想象它还没有在范围内,或者它已经超出了范围。 Try putting a breakpoint on the line immediately after the line you posted where you assign to query. 尝试在您分配给查询的行所在行之后立即在行上放置断点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM