if 中的 LINQ where 子句条件

LINQ where clause condition in if

我有一个 class 包含以下属性:

public class Suborder
{
     public List<OrderLineItem> OrderLineItemList { get; set; }
     public string ProviderCode { get; set; }
}


public class OrderLineItem
{
    public List<OrderLineItem> BundleComponentList { get; set; }
    public string Product { get; set; }
}

我想遍历 BundleComponentList 以检查它的任何项目是否具有等于 Shoes 的 Product 值。我这样试过但出现错误

if (suborder.OrderLineItemList.Any(x => x.Product == "Shoes") || suborder.OrderLineItemList.Where(x=>x.BundleComponentList.Any(y=>y.Product == "Shoes")))

Operator '||' cannot be applied to operands of type 'bool' and 'System.Collections.Generic.IEnumerable

我的 LINQ 有什么问题?

使用 Any 而不是 Where 作为 Where returns 序列,而不是 bool

suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))

Where() 不是 return 布尔值,而是 IEnumerable,因此不能在 if 子句中使用。你应该在你的情况下使用 Any()

if (suborder.OrderLineItemList.Any(x => x.Product == "Shoes") || 
    suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))

另请注意,上述 if 子句假定子订单永远不会为空。

我会为此结合使用 lambda 和 LINQ。更容易阅读和了解发生了什么:

var orders = from o in suborder.OrderLineItemList
             where
               o.Product == "Shoes" ||
               o.BundleComponentList.Any(c => c.Product == "Shoes")
             select o;

bool isShoesOrder = orders.Any();