Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - SelectMany from multiple properties in same object

Tags:

c#

linq

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?

like image 470
AaronS Avatar asked Jun 13 '11 15:06

AaronS


1 Answers

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.

like image 171
Jon Skeet Avatar answered Oct 18 '22 03:10

Jon Skeet