[英]LINQ where clause condition in if
我有一個包含以下屬性的類:
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以檢查其任何項目的Product值是否等於Shoes。 我嘗試這樣,但出現錯誤
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有什么問題?
使用Any
代替Where
as Where
返回一個序列,而不是bool
。
suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))
Where()
不返回布爾值,而是IEnumerable
,因此不能在if子句中使用。 在這種情況下,應使用Any()
。
if (suborder.OrderLineItemList.Any(x => x.Product == "Shoes") ||
suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))
還請注意,上述if子句假定子順序永遠不會為null。
我將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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.