亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

if 中的 LINQ where 子句條件

if 中的 LINQ where 子句條件

C#
元芳怎么了 2022-06-12 10:52:55
我有一個包含以下屬性的類: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")))



查看完整回答
反對 回復 2022-06-12
?
九州編程

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();


查看完整回答
反對 回復 2022-06-12
?
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 永遠不會為空。


查看完整回答
反對 回復 2022-06-12
  • 3 回答
  • 0 關注
  • 234 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號