LINQ - SelectMany of several properties in one object

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

Using these objects, I want to get a list of all the unique tax rates used for the entire order, including rates on goods and delivery.

The following LINQ query will get me the list I need, but only for commodity 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 containing a list of unique tax rates that contains both the product and the shipping rates?

+6
source share
1 answer

It looks 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, a change is a Concat call that combines two sequences together.

+11
source

Source: https://habr.com/ru/post/890415/


All Articles