Linq to object Multiple Where 短路评估

当在 Linq to object 表达式中包含多个 Where 子句时,它们会像 && 运算符一样评估短路吗?含义将仅在条件 A 返回 true 时评估条件 B

例如collection.Where(condition1).Where(condition2)

(不谈论即使使用 && 运算符short-circuiting-in-linq-where也不会这样做的 Linq to sql )


蓝山帝景
浏览 164回答 1
1回答

三国纷争

让我们再看一些代码。我们将测试这两种情况:首先,我们将使用两个 if 语句来测试 &&我们将使用两个 Where 调用所以:var elements = new List<string>(new[] { "A", "B", "C" });Console.WriteLine("C#'s &&");elements.Where(x => {&nbsp; &nbsp; if (x == "A")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("ConditionA is true");&nbsp; &nbsp; &nbsp; &nbsp; if (1 == 1)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("ConditionB is true");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("ConditionB is false");&nbsp; &nbsp; }&nbsp; &nbsp; Console.WriteLine("ConditionA is false");&nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}).ToList();Console.WriteLine();Console.WriteLine("Double Linq.Where");elements.Where(x => {&nbsp; &nbsp; if (x == "A")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("ConditionA is true");&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; Console.WriteLine("ConditionA is false");&nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; .Where(x => {&nbsp; &nbsp; &nbsp; &nbsp; if (1 == 1)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("ConditionB is true");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("ConditionB is false");&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }).ToList();结果如下:C#'s &&ConditionA is trueConditionB is trueConditionA is falseConditionA is falseDouble Linq.WhereConditionA is trueConditionB is trueConditionA is falseConditionA is false正如你所看到的,它是一样的。未通过 ConditionA 的元素不会针对 ConditionB 进行测试。你可以在这里试试这个:https ://dotnetfiddle.net/vals2r
打开App,查看更多内容
随时随地看视频慕课网APP