简体   繁体   English

使用LINQ在列表中过滤列表

[英]Filter list within list using LINQ

I have the following classes: 我有以下课程:

class Order
{
    public string AccountNumber;
    public string AccountName;
    public List<OrderLine> OrderLines = new List<OrderLine>();
    public DateTime StartDate;
    public DateTime EndDate;       
}

class OrderLine
{
     public string Description;
     public string ProductCode;
     public double Duration;
     public int Quantity;
}

What would be the LINQ code to get the list of Order objects based upon the following conditions? 根据以下条件获取Order对象列表的LINQ代码是什么?

  1. [Order] AccountNumber is equal to "1234" [订单]帐号等于“ 1234”
  2. [OrderLine] Quantity greater than 10 [OrderLine]数量大于10

Assuming you want all records that match both conditions (for any satisfactory OrderLine , otherwise change to All() ): 假设您希望所有记录都符合这两个条件(对于任何令人满意的OrderLine ,否则请更改为All() ):

public static void IEnumerable<Order> GetQualifying(this IEnumerable<Order> orders, string accountNo, int minQty) {
    return orders.Where(o =>
        o.AccountNumber == accountNo
        && o.OrderLines.Any(ol => ol.Quantity >= minQty);
}

Be careful not to get an off-by-one error as I have interpreted "minimum quantity" literally. 请小心不要出现一个错误,因为我从字面上解释了“最小数量”。

Also, the this syntax is great for writing extension methods , which allow you to invoke like this: 另外, this语法非常适合编写扩展方法 ,该方法允许您这样调用:

Order[] orders = //stuff;
Order[] qualifiedOrders = orders.GetQualifying("1234", 9).ToArray();

Note that I recommend using as ToArray() as soon as you can no longer benefit from lazy evaluation , otherwise doing subsequent operations on raw IEnumerable<> will cause reevaluation (read: enumerating the collection again). 请注意,我建议您在不再能从延迟评估中受益时,立即将其用作ToArray() ,否则对原始IEnumerable<>进行后续操作将导致重新评估 (阅读:再次枚举集合)。

You could go with: 您可以选择:

list.Where(x => x.AccountNumber == "12345" && x.OrderLines.Any(o => o.Quantity > 10));

or: 要么:

list.Where(x => x.AccountNumber == "12345" && x.OrderLines.All(o => o.Quantity > 10));

depending on whether you want to retrieve all objects that have an AccountNumber of 12345 and any OrderLine quantity greater than 10 or if all OrderLine quantity is greater than 10 取决于您是否要检索AccountNumber12345OrderLine数量大于10的所有对象,还是所有OrderLine数量大于10的对象

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

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