簡體   English   中英

如何在Linq查詢中的where條件中使用數組

[英]How to use array in where condition in Linq queries

這是我的linq查詢。

var data =
  (from obj in lstEventsDataForGrid
   where obj.strDateCode.Contains(thisWeekend[0] == null ? "" : thisWeekend[0])
         || obj.strDateCode.Contains(thisWeekend[1] == null ? "$" : thisWeekend[1])
         || obj.strDateCode.Contains(thisWeekend[2] == null ? "$" : thisWeekend[2])
            && strArr.Contains(obj.strEventType.ToString().ToUpper())
   orderby obj.dtmStartDate ascending
   select obj).GroupBy(x => x.strEventCode)
              .Select(y => y.First()).ToArray();

預期結果

strEventType是否不在strArr中不應該出現。

但是,即使該類型不在數組中,它也即將到來。

問題我注意到的是,如果我刪除一個WHERE條件即obj.strDateCode.Contains(...)的另一種情況是工作。

我要去哪里錯了? 請提出一些建議!

我認為您缺少一些括號。 您是說要對待三個||嗎? 條件作為一種選擇?

where (A || B || C) && D

嘗試where此處之后放置一個:

where (obj.strDateCode.Contains(thisWeekend[0]

還有第二個在這里:

: thisWeekend[2]))

我使用空字符運算符重寫了您的查詢,以使其更具可讀性。 我還添加了行號以指出我在這里的錯誤:

1.     var data = (
2.         from obj in lstEventsDataForGrid
3.         where obj.strDateCode.Contains(thisWeekend[0] ?? "") ||
4.              obj.strDateCode.Contains(thisWeekend[1] ?? "$") ||
5.              obj.strDateCode.Contains(thisWeekend[2] ?? "$") &&
6.              strArr.Contains(obj.strEventType.ToString().ToUpper())
7.         orderby obj.dtmStartDate ascending
8.         select obj
9.         ).GroupBy(x => x.strEventCode).Select(y => y.First()).ToArray();

您需要更改以下幾行:

3.         where (obj.strDateCode ...          // add '('
5.         ... thisWeekend[2] ?? "$")) &&      // add ')'

這樣,您的&&將克服其余條件。

您的where謂詞包含錯誤:

obj.strDateCode.Contains(thisWeekend[0] == null ? "" : thisWeekend[0])
|| obj.strDateCode.Contains(thisWeekend[1] == null ? "$" : thisWeekend[1])
|| obj.strDateCode.Contains(thisWeekend[2] == null ? "$" : thisWeekend[2]) 
&& strArr.Contains(obj.strEventType.ToString().ToUpper())

這是以下形式的表達式:

where Condition1 || Condition2 || Condition3 && Condition4.

在C#中, &&運算符優先於|| 運算符,所以這等效於

where Condition1 || Condition2 || (Condition3 && Condition4).

在這種情況下,僅當Condition3為true時才評估Condition4。 如果Condition1或Condition2為true,則整個謂詞將返回true,並且表達式的其余部分將短路。

您可能想要的是:

where (Condition1 || Condition2 || Condition3) && Condition4

或者,擴展到您的示例:

(obj.strDateCode.Contains(thisWeekend[0] == null ? "" : thisWeekend[0])
 || obj.strDateCode.Contains(thisWeekend[1] == null ? "$" : thisWeekend[1])
 || obj.strDateCode.Contains(thisWeekend[2] == null ? "$" : thisWeekend[2]) 
) && strArr.Contains(obj.strEventType.ToString().ToUpper())

這將確保如果strArr未包含obj則不會返回該obj
您的問題表明所要求的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM