Jerry Nixon on Windows: Lambda All(x => x) and Any(x => x)

Jerry Nixon on Windows

Monday, September 12, 2011

Lambda All(x => x) and Any(x => x)

I remember early on that Select() seemed to me the logical approach to filter a Queriable collection. Of course, Where() turned out to be the way. But had I noticed it, I think All() would have confused me the same. I would have through Any() with a predicate would have resulted in "all" the matching records. Fortunately, I didn't hit that wall. I have used Any() for years, but recently I recognized the inverse relationship of All() to Any(). And, of course, none is to select data ;-)

The Lambda method All() is used to test if all members meet a condition:

    if (!values.All(x => x != null))
        return "none may be null";

This would check that none are null.

Similarly, the Lambda method Any() is used to test if any members meet a condition:

    if (values.Any(x => x == null))
        return "none may be null";

This would be identical logic as we did with All().