Why . all in an empty list returns true?

Asked

Viewed 154 times

0

I was having an error in a business rule, and when investigating, I arrived at the following code snippet, the intention of which is to verify that all the processes on a list are active:

return processos.All(proc => proc.Ativo)

While debugging, I discovered that processos had zero elements. It is easy to correct, just change the conditional to:

return processos.Any() && processos.All(proc => proc.Ativo)

However, the documentation official states that the .All:

Determines whether all elements of a sequence meet a condition.

If a list is empty, how can all elements meet a condition? Or I have some misconception?

I made a playable example on Rextester.

  • 3

    Interestingly you can invert the Portuguese in order to answer the question. If the list is empty there is no element, so the .All test if none meets the condition. And in fact none meets. D

2 answers

4


Explanation

According to the documentation if the sequence is empty, value will be returned true.

Value Returned

Type: System.Boolean

true if all elements of the source sequence pass the test in the specified predicate or if the sequence is empty; otherwise, false.

Source: Microsoft Docs - Enumerable.All Method (Ienumerable, Func)

  • It’s true. I missed this part

2

According to the documentation of Enumerable.All method (Ienumerable, Func)

Value Returned

Type: System.Boolean

true if all elements of the source sequence pass the test on the specified predicate or if the sequence is empty; otherwise false.

If we analyze the source code of this . net Core method, we can see:

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
        {
            if (source == null)
            {
                throw Error.ArgumentNull(nameof(source));
            }

            if (predicate == null)
            {
                throw Error.ArgumentNull(nameof(predicate));
            }

            foreach (TSource element in source)
            {
                if (!predicate(element))
                {
                    return false;
                }
            }

            return true;
        }

Decorticating:

  1. exceptions will be generated if Source or Predicate are void;
  2. For each element of Source check whether the Predicate is false. If yes return false
  3. if all elements fail the test within the loop, a return true is executed

For the case of an empty list (which is different from a null list), the unexecuted loop and thereturn true is executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.