【发布时间】:2016-03-17 15:25:21
【问题描述】:
我有一个小例子可以使用 || Where() 的运算符,但可能有问题:
var list = new List<string>
{
"One",
"Two",
"Three"
};
string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
foreach(var number in numbers)
{
Console.WriteLine(number);
// output:
// One
// Two
// Three
}
s = null;
numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
foreach(var number in numbers)
{
Console.WriteLine(number);
// output:
// One
// Two
// Three
}
在第一种情况下,为什么 !string.IsNullOrEmpty(x) 在我们有 x == s 为真时仍然检查?
我明白了:
if (A && B)
{
// we need A and B are true
}
if (A || B)
{
// we need A is true or B is true
// if A is true, no ned to check B is true or not
}
所以,我的问题是:我误会了什么?
【问题讨论】:
-
因为它会评估列表中每个元素的查询。
-
嗯,这个问题是根据记录提出的。所以
"Two"=>"Two" == "One" || !string.IsNullOrEmpty("Two") -
!String.IsNullOrEmpty(x)对于列表中的每个字符串始终为 true。您的 LINQ 是“当字符串等于 One 或字符串不为空且不为空时包含” -
为什么你会认为第一个列表项是根据你的 Where 子句的后半部分检查的?它似乎按预期工作:第一项通过,因为它等于
s,其他通过 Where 检查的第二部分,因为它们不为空。 -
为什么投反对票?这是一个完全有效的问题,带有很好的示例代码。 OP 不了解 Where 方法的工作原理这一事实并不值得反对。
标签: c# linq logical-operators