IEnumerable.All() and False Positives

I recently ran across an obscure feature of .NET that appeared to be returning false positives for Enumberable.All().
The issue: a client wanted to display a list of objects but only if all the objects meet a certain criteria. This works as expected except when the list is empty. If the list is empty All() returns True. This could be misconstrued as a false positive without any additional checks.
In reality this behaves as designed; just not what you’d immediately expect. Per Microsoft’s documentation: “True if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, False.”
The key takeaway: “True… if the sequence is empty.” James Michael Hare has a great explanation on why this makes sense.
How did I get around this? Add an Any check before using All.
See the example below to illustrate the point.
The following returns True if all the People objects have a LastName value.
if(People.All(p => !string.IsNullOrWhiteSpace(p.LastName)))
{
     Do something...
Per Microsoft’s documentation, the above also returns true if the People list is empty. To compensate, I added an Any check ahead of the People.All predicate.
if(People.Any()
     && People.All(p => !string.IsNullOrWhiteSpace(p.LastName)))
{
     Do something...
Are there better ways to handle this? Probably. For example, handle no results when first creating the list. Or, check for Any early in the method and return if it’s an empty list. But sometimes, you have to play the cards you’re dealt.

2 comments

  1. Wow, you’re right. I guess it does make sense and thanks for the good explanation. So, does the People.Any() check work as is or do you have to put People.Any(p => !string.IsNullOrWhiteSpace(p.LastName))?

    Liked by 1 person

    1. The purpose of Any() was to verify the list was not empty before using All(); no additional Any() predicate needed. You could rewrite it with a new Any() predicate and not use All(). I had to keep All() for other client concerns.

      Like

Leave a reply to Dave Cancel reply