我有一個包含以下屬性的類: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 有什么問題?
3 回答
翻過高山走不出你
TA貢獻1875條經驗 獲得超3個贊
使用Any而不是WhereasWhere返回一個序列,而不是一個bool.
suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))
九州編程
TA貢獻1785條經驗 獲得超4個贊
我會將 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();
RISEBY
TA貢獻1856條經驗 獲得超5個贊
Where()不返回布爾值,而是返回 an IEnumerable,因此不能在 if 子句中使用。你應該Any()在你的情況下使用。
if (suborder.OrderLineItemList.Any(x => x.Product == "Shoes") || suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))
另請注意,上述 if 子句假定 suborder 永遠不會為空。
- 3 回答
- 0 關注
- 234 瀏覽
添加回答
舉報
0/150
提交
取消
