IEnumerable.All() gotcha

Today as I was inspecting why some condition was evaluated to true instead of false I found out a strange thing. The code is something like :

var someList = new List<Person>();
if (someList.All(v => v.Age > 18))
{
    Console.WriteLine("All are 18 or older.");
}
else
{
    Console.WriteLine("At least one is less than 18.");
}

I was expecting that in case of an empty collection the All method would return false. But it doesn’t. The “All are 18 or older.” string would be printed.

In my case one more simple condition solved this issue :

    if (someList.Any() && someList.All(v => v.Age > 18))

After this I read the manual (RTFM) and according to MSDN (in a community comment however) :

It’s important to note that Enumerable.All() returns true for empty sequences

So it’s a “doh” moment for me.

Watch out for this in your code.

  1. learned something new today, nice post, keep them coming:)

  2. Proababil se comporta asa pentru a fi consistent cu ALL din SQL, care la fel returneaza true pentru subquery-uri ce nu returneaza nimic.
    Nu stiu daca asta e corect din punct de vedere al logicii matematice (predicate, teoria multimilor etc.) dar..

  3. First of all, >18 means older than 18, not 18 and older. Then, the All(condition) construct is equivalent to !Any(!condition). In that case, the complete “if (someList.Any()&&!someList.Any(v=>v.Age<18))" feels weird. Then again, I can't think of anything better.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.