if 中的 LINQ where 子句条件

我有一个包含以下属性的类:


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")))

运算符“||” 不能应用于“bool”和“System.Collections.Generic.IEnumerable”类型的操作数


我的 LINQ 有什么问题?


元芳怎么了
浏览 281回答 3
3回答

翻过高山走不出你

使用Any而不是WhereasWhere返回一个序列,而不是一个bool.suborder.OrderLineItemList.Any(x&nbsp;=>&nbsp;x.BundleComponentList.Any(y&nbsp;=>&nbsp;y.Product&nbsp;==&nbsp;"Shoes")))

九州编程

我会将 lambda 与 LINQ 结合起来。更容易阅读和查看发生了什么:var orders = from o in suborder.OrderLineItemList&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;where&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;o.Product == "Shoes" ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;o.BundleComponentList.Any(c => c.Product == "Shoes")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select o;bool isShoesOrder = orders.Any();

RISEBY

Where()不返回布尔值,而是返回 an&nbsp;IEnumerable,因此不能在 if 子句中使用。你应该Any()在你的情况下使用。if&nbsp;(suborder.OrderLineItemList.Any(x&nbsp;=>&nbsp;x.Product&nbsp;==&nbsp;"Shoes")&nbsp;||&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;suborder.OrderLineItemList.Any(x&nbsp;=>&nbsp;x.BundleComponentList.Any(y&nbsp;=>&nbsp;y.Product&nbsp;==&nbsp;"Shoes")))另请注意,上述 if 子句假定 suborder 永远不会为空。
打开App,查看更多内容
随时随地看视频慕课网APP