C#Linq查询子列表

时间:2016-09-12 11:14:17

标签: c# linq

我有一个类结构,如下所示,我有一个OrderItem列表,每个项目都有折扣列表

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

如果我想获得IsActive标志为true的所有折扣列表,我将如何在Linq查询中执行此操作?

目前这就是我所拥有的,但是需要删除2个foreach语句非常难看。

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

1 个答案:

答案 0 :(得分:0)

这是一行的linq声明:

order.OrderItems.SelectMany(item => item.Discounts.Where(discount => discount.IsActive));