0

Let's say there's a function that generates prime numbers:

static void Main() {
    var n = 10;

    var primeNumbers = new List<int>();
    int current = 2;


    // Console.WriteLine(primeNumbers.All((x) => current % x != 0));
    while (primeNumbers.Count <= n) {
        if (primeNumbers.All((x) => current % x != 0)) {
            primeNumbers.Add(current);
            Console.WriteLine("Prime number: " + current);
        }

        current++;
    }
}

On the very first iteration within while the list is empty. Why method Enumerable.All gives back True (all elements of a sequence satisfy a condition which is current % x != 0). What the value of x?

Sébastien
  • 893
  • 2
  • 9
  • 13

1 Answers1

3

The reason why you get true is provided by the documentation:

true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.

This makes sense logically, too, because All is supposed to mean the same thing as !Any(...). Since Any would evaluate to false for an empty collection, it follows that All should evaluate to true under the same circumstances.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I know that. But there's the expression `current % x != 0` which is on the first iteration becoming `2 % x != 0`. In order to add the first element into the list and increase the `current` it have to pass `if` statement. But neither `2 % 1` or ` `2 % 0` `!= 0`. – Sébastien Feb 07 '16 at 14:35
  • 2
    @J.Doe - If the list is empty the lambda is never called so `x` is never bound to anything. `All` can return true immediately without invoking the predicate. – Lee Feb 07 '16 at 14:37