LINQ从子列表中选择

时间:2009-11-05 11:27:20

标签: c# .net linq

如何使Linq查询从类别中获取所有Productpricediscounts?

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 个答案:

答案 0 :(得分:14)

您需要使用SelectMany才能访问priceDiscounts

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

答案 1 :(得分:4)

您需要Enumerable.SelectMany

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