[英]How to set conditional filter in where clause using linq?
我的身體狀況不佳,稱為accessories
如果為真,那么我想確保一個單元格值不為空,否則它可以為空。 我有以下幾點:
var items = (from a in allRowsrows
where accessories == true ? a["MASTERID"].ToString() != "": a["MASTERID"].ToString() == "" &&
a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString() ||
a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()
select new ItemsToUpdate
{
isAccessory = accessories,
Item = a
}
).ToList();
問題:好吧,簡單地說,使用上述方法時,它無法正確過濾。
ITEMNO cell, `NEWITEMNO` cell are the same , LABEL cell and `NEWVISITEMNO` cell are also the same
然后這應該給我一個包含0個項目的列表,但我仍在列表中找到項目。
我究竟做錯了什么?
編輯:
修改后的代碼:
var items = (from a in allRows
where accessories == true ? a["MASTERID"].ToString() != "": true &&
(a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString()) ||
(a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString())
select new ItemsToUpdate
{
isAccessory = accessories,
Item = a
}
).ToList();
仍然錯誤的過濾。
這就是為什么您無法獲得正確結果的原因。 這種情況:
where accessories == true ? a["MASTERID"].ToString() != "": a["MASTERID"].ToString() == "" &&
a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString() ||
a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()
意味着:
如果附件為真,則檢查MASTERID是否為空。 這就對了。 但是,這就是錯誤的所在,如果附件不正確,請檢查以下整個情況:
a["MASTERID"].ToString() == "" &&
a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString() ||
a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()
評估如下:
(a["MASTERID"].ToString() == "" &&
a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString()
)
OR
a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()
換句話說,如果MASTERID為空並且ITEMNO與NEWITEMNO不同,則它將永遠不會檢查LABEL。 您在問題中編輯的代碼沒有區別,仍然與上述含義相同。
現在您的問題是,為什么謎題的答案會為您提供正確的結果。 他的情況如下:
where accessories ? a["MASTERID"].ToString() != "" : true
where a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString() || a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()
這意味着:
如果附件為真,則檢查MASTERID是否為空。 否則,使用值true
。 另外,請檢查以確保ITEMNO與NEWITEMNO不相同或LABEL與NEWVISITITEMNO不相同。
所以本質上是這樣做的:
(accessories ? a["MASTERID"].ToString() != "" : true)
&&
(
a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString() ||
a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()
)
我不知道您的完整要求,但即使是謎團的答案,也可能會產生錯誤的結果(也可能不會)。 這完全取決於您何時會遇到具體情況。 也許,我的解釋可以指導您。
這是你所追求的嗎?
var items =
(
from a in allRowsrows
where accessories ? a["MASTERID"].ToString() != "" : true
where a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString() || a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()
select new ItemsToUpdate
{
isAccessory = accessories,
Item = a
}
).ToList();
您是否嘗試在where子句中使用方括號?
var items = (from a in allRows
where (accessories == true ? a["MASTERID"].ToString() != "": true &&
(a["ITEMNO"].ToString() != a["NEWITEMNO"].ToString()) ||
(a["LABEL"].ToString() != a["NEWVISITEMNO"].ToString()))
select new ItemsToUpdate
{
isAccessory = accessories,
Item = a
}
).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.