我有一个使用||的小例子 运算符,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
}
所以,我的问题是:我误解了什么?
您说的很对:
a || b
不会评估b
是否a
为true
,但:
Where
LINQ使用Lambda表达式检查Enumerable中的每个元素,而不管先前的结果如何。因此,当您执行以下操作时:
string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
只要Where
lambda表达式有效,它就会检查查询中的每个元素:
x == s || !string.IsNullOrEmpty(x)); //x = "One", x == s is true
x == s || !string.IsNullOrEmpty(x)); //x = "Two", !string.IsNullOrEmpty(x) is true
x == s || !string.IsNullOrEmpty(x)); //x = "Three", !string.IsNullOrEmpty(x) is true
这样就得到了所有要素。
TakeWhile
如果您想在不再满足条件时立即停止获取查询结果,请考虑使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句