Why does .all in an empty list return true?

0

I was having an error in a business rule, and by investigating, I came up with the following code snippet, which is intended to check if all processes in a list are active:

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

When debugging, I discovered that% w / o% had zero elements. It's easy to fix, just change the conditional to:

processos

However, the official documentation states that return processos.Any() && processos.All(proc => proc.Ativo) :

  

Determines whether all elements of a string meet a condition.

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

I made a reproducible example on Rextester .

    
asked by anonymous 12.07.2018 / 20:26

2 answers

4

Explanation

According to the documentation if the string is empty, it will return true .

  

Returned

     

Type: System.Boolean      

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

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

    
12.07.2018 / 20:33
2

According to the documentation for the Enumerable.All (IEnumerable, Func)

method

  

Return Value

     

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.

If we analyze the source code of this .NET 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;
        }

Decorating:

  • exceptions will be generated if Source or Predicate are null;
  • For each element of Source check that Predicate is false. If yes, return false
  • If all elements do not pass the test inside the loop, a return true is executed
  • For the case of an empty list (which is different from a null list), the loop is not executed and return true is executed.

        
    12.07.2018 / 20:51