如何在Linq查询中的where条件中使用数组

时间:2013-05-23 11:08:33

标签: c# .net linq

这是我的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();

预期结果

strErr是否不在strArr中,不应该出现。

但即使该类型不在数组中也会出现。

问题我注意到,如果我删除了一个条件,即obj.strDateCode.Contains(...)其他条件正在运行。

我哪里错了?请提出建议!

3 个答案:

答案 0 :(得分:3)

我认为你错过了一些括号。你的意思是对待三个||条件作为一种选择?如在

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

尝试在where之后放一个:

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

和第二个:

: thisWeekend[2]))

答案 1 :(得分:3)

我使用null-coalesce运算符重写了您的查询,使其更具可读性。我还添加了行号来指出我认为错误的地方:

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 ')'

这样,您的&&将胜过其他条件。

答案 2 :(得分:3)

您的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为真时才评估Condition4。如果Condition1或Condition2为真,则整个谓词将返回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())

如果obj中未包含strArr,这将确保不会返回{{1}} 您的问题表明是必需的结果。

相关问题