LINQ从子列表中选择

7

我该如何使用Linq查询来获取某个类别下的所有产品价格折扣?

public class ProductCategory
{
    public List<Product> categoryProducts;
}

public class Product
{
    public List<Productprice> productPrices;
}

public class Productprice
{
    public List<Productpricediscount> priceDiscounts;
}

我的查询应该类似于:

categoryProducts.Select(p => p.productPrices).Select(x => x.?!?!

问题在于我本来期望x.intellisense会建议priceDiscounts,但是我却得到了“list”值(例如:“Any”,“Select”,“Distinct”等)。

2个回答

20

你需要使用SelectMany来访问priceDiscounts

var query = categoryProducts
            .SelectMany(x => x.productPrices)
            .SelectMany(y => y.priceDiscounts);

我认为你需要使用第二个SelectMany而不是Select,以便将结果展开。 - Winston Smith
@Winston:你说得对。那实际上是我最初写的,但后来我进行了编辑并改为了“Select”。我刚刚又改回了“SelectMany”。 - LukeH

4
你需要使用 Enumerable.SelectMany
var result = categoryProducts.SelectMany(x => x.productPrices)
             .SelectMany(x => x.priceDiscounts);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接