Category Archives: LINQ

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.

WP Like Button Plugin by Free WordPress Templates