Search code examples
c#linq

LINQ - SelectMany from multiple properties in same object


Assume you have the following simple objects:

 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; }
}

With these objects, I want to be able to get a list of all the unique tax rates used on the entire order, including both merchandise and shipping tax rates.

The following LINQ query will get me the list I need, but only for merchandise taxes:

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

How can I get a list that contains list of unique tax rates that contains both merchandise and shipping rates?


Solution

  • It sounds like you want this:

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

    Basically the change is the call to Concat which will concatenate two sequences together.