I have a class structure as below whereby I have a list of OrderItems and each item has a list of Discounts
public class Order
{
public IList<OrderItem> OrderItems = new List<OrderItem>();
}
public class OrderItem
{
public IList<Discount> Discounts = new List<Discount>();
}
public class Discount
{
public string Desc { get; set; }
public decimal Amount { get; set; }
public bool IsActive { get; set; }
}
If I want to get a list of all discounts with an IsActive flag of true, how would I do this in a Linq query?
Currently this is what I have but it is very ugly with 2 foreach statements that need to be removed.
IList<Discount> activeDiscounts = new List<Discount>();
foreach (OrderItem item in order.OrderItems)
{
var aDiscounts = from discount in item.Discounts.AsEnumerable()
where discount.IsActive == true
select discount;
foreach (Discount discount in aDiscounts)
{
activeDiscounts.Add(discount);
}
}
这是一行 linq 语句:
order.OrderItems.SelectMany(item => item.Discounts.Where(discount => discount.IsActive));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.