在Linq中的对象表达式中包含多个Where子句时,它们是否会像&&运算符那样评估短路?仅当条件A返回true时,才对条件B求值。
例如collection.Where(condition1).Where(condition2)
(不谈论Linq to sql,即使使用&&运算符short-circuiting-in-linq-where也不会这样做)
答案 0 :(得分:1)
让我们看看更多代码。我们将测试两种情况:
所以:
var elements = new List<string>(new[] { "A", "B", "C" });
Console.WriteLine("C#'s &&");
elements.Where(x => {
if (x == "A")
{
Console.WriteLine("ConditionA is true");
if (1 == 1)
{
Console.WriteLine("ConditionB is true");
return true;
}
Console.WriteLine("ConditionB is false");
}
Console.WriteLine("ConditionA is false");
return false;
}).ToList();
Console.WriteLine();
Console.WriteLine("Double Linq.Where");
elements.Where(x => {
if (x == "A")
{
Console.WriteLine("ConditionA is true");
return true;
}
Console.WriteLine("ConditionA is false");
return false;
})
.Where(x => {
if (1 == 1)
{
Console.WriteLine("ConditionB is true");
return true;
}
Console.WriteLine("ConditionB is false");
return false;
}).ToList();
以下是结果:
C#'s &&
ConditionA is true
ConditionB is true
ConditionA is false
ConditionA is false
Double Linq.Where
ConditionA is true
ConditionB is true
ConditionA is false
ConditionA is false
就像您看到的一样。未通过ConditionA的元素不会针对ConditionB进行测试。
您可以在这里尝试:https://dotnetfiddle.net/vals2r