Does the C # LINQ Aggregate method execute execution after the result no longer changes?

I know that if I bind the operators &&or ||together in the same operator, C # stops calculating the operator and returns the corresponding result if it evaluates the expression and no matter what the following expressions, the result will not change. For instance:

var result = false && foo() && bar();

In this expression, foo()they bar()will never be executed, since the first expression is false. My question is, will it Enumerable.Aggregate<TSource, TAccumulate>do the same when running through the bools list, or will it evaluate all expressions independently? For instance:

var result = new List<bool>
{
    false,
    foo(),
    bar()
}.Aggregate(true, (acc, x) => acc && x);
+4
source share
3 answers

&& , . x acc false.

, . Aggregate , .

All , All, Aggregate, , false, ( Or, true).

+5

, Aggregate , && . , :

, result1 x() . - acc.

2 && x() .

Console.WriteLine("acc && x()");
var result1 = new List<Func<bool>>
{
    () => {Console.WriteLine("One"); return true;},
    () => {Console.WriteLine("Two"); return false;},
    () => {Console.WriteLine("Three"); return false;}
}.Aggregate(true, (acc, x) => acc && x());
Console.WriteLine();
Console.WriteLine("x() && acc");
var result2 = new List<Func<bool>>
{
    () => {Console.WriteLine("One"); return true;},
    () => {Console.WriteLine("Two"); return false;},
    () => {Console.WriteLine("Three"); return false;}
}.Aggregate(true, (acc, x) => x() && acc);

:

acc && x()
One
Two

x() && acc
One
Two
Three
0

, , Aggregate(), , .

, # - , , - , .

0

Source: https://habr.com/ru/post/1680517/


All Articles