0

Consider the following code:

static void Main(string[] args)
{
    List<string> items = new List<string>();
    string result = null;

    if(items.All(o => o == "ABC"))
    {
        result = "All";
    }
    else if(items.Any(o => o == "XYZ"))
    {
        result = "Any";
    }

    Console.WriteLine(result);
    Console.Read();
}

This prints "All".

Why does an empty list satisfy an "All" condition where o == "ABC"

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
  • 2
    Look at the source code [here](http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,be4bfd025bd2724c,references) – Jenish Rabadiya Dec 01 '15 at 09:45
  • _Why_ is subjective, isn't it? Is the glass half-full or half-empty? `All` satisfy your condition because there are none. You can always check first if the list is empty. – Tim Schmelter Dec 01 '15 at 09:47
  • I think you need to think about it in the opposite way. `.All(...)` is `true` so long as none exist that are `false`. If the list is empty then none exist that are `false` so it is `true`. – Enigmativity Dec 01 '15 at 09:48

2 Answers2

7

According to MSDN:-

Enumerable.All

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

So in your case since items is an empty collection it is returning true.

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
5

This is by design and also consistent with how the universal quantifier ∀ works in mathematics on sets.

Joey
  • 344,408
  • 85
  • 689
  • 683