[英]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:以下 LINQ 查询将为我提供所需的清单,但仅适用于商品税:
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?如何获取包含包含商品和运费的唯一税率列表的列表?
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.基本上变化是调用
Concat
将两个序列连接在一起。
It can also be used like this;也可以这样使用;
var TaxRates = MyOrder.Customers
.ToList()
.SelectMany(x => new[] { x.SaleLines, x.MerchTax })
.GroupBy(tax => tax.Rate)
.Select(group => group.Key);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.