LINQ - 从同一对象中的多个属性中选择多个

时间:2011-06-13 15:07:03

标签: c# linq

假设您有以下简单对象:

 class Order
{
    public Customer[] Customers { get; set; }
}

class Customer
{
    public SaleLine[] SaleLines { get; set; }
}

class SaleLine
{
    public Tax[] MerchTax { get; set; }
    public Tax[] ShipTax { get; set; }
}

class Tax
{
    public decimal Rate { get; set; }
    public decimal Total { get; set; }
}

通过这些对象,我希望能够获得整个订单中使用的所有独特税率的列表,包括商品和运费税率。

以下LINQ查询将获取我需要的列表,但仅用于商品税:

            var TaxRates = MyOrder.Customers
            .SelectMany(customer => customer.SaleLines)
            .SelectMany(saleline => saleline.MerchTax)
            .GroupBy(tax => tax.Rate)
            .Select(tax => tax.First().Rate

如何获得包含商品和运费的唯一税率列表的列表?

1 个答案:

答案 0 :(得分:12)

听起来你想要这个:

var TaxRates = MyOrder.Customers
            .SelectMany(customer => customer.SaleLines)
            .SelectMany(saleline => saleline.MerchTax.Concat(saleline.ShipTax))
            .GroupBy(tax => tax.Rate)
            .Select(group => group.Key);

基本上,更改是对Concat的调用,它将两个序列连接在一起。