简体   繁体   English

针对子列表的 C# Linq 查询

[英]C# Linq Query against sub list

I have a class structure as below whereby I have a list of OrderItems and each item has a list of Discounts我有一个如下的类结构,其中我有一个 OrderItems 列表,每个项目都有一个 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?如果我想获取 IsActive 标志为 true 的所有折扣的列表,我将如何在 Linq 查询中执行此操作?

Currently this is what I have but it is very ugly with 2 foreach statements that need to be removed.目前这就是我所拥有的,但它非常难看,需要删除 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);
            }
        }

这是一行 linq 语句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM