What is the opposite method of Any in LINQ?

Full article

If you are (or hope to be) a .NET developer, knowing LINQ is a huge time-saver. It's a syntax that allows you to manipulate data in a fashion that'll be familiar to anyone who's worked in a database.


One of the many nice functions in LINQ is a single word that iterates through a collection, returning true if at least one item in the collection matches the condition you specify.

var currencies = new[] { "USD", "EUR", "JPY" };

Console.WriteLine(currencies.Any(x => x == "MXN"));  // False

But what's the opposite of Any<T>()?

What if, instead of finding out whether the list of currencies includes "peso", you wanted to make sure the list of currencies did not include "peso"? You could negate the above, but you might think that reads a bit funny... and I'd agree.

var currencies = new[] { "USD", "EUR", "JPY" };

Console.WriteLine(!currencies.Any(x => x == "MXN"));  // True


The only way to make sure that a list doesn't include a particular value, or that no item in the collection matches a particular condition, is to check every single item in the collection... and that's what All<T>() is for.

var currencies = new[] { "USD", "EUR", "JPY" };

Console.WriteLine(currencies.All(x => x != "MXN"));          // True

Console.WriteLine(currencies.All(x => !x.StartsWith("M")));  // True

Try it out

Try it out yourself below. And to learn more, read about All and Any.


Grant Winney

I write when I've got something to share - a personal project, a solution to a difficult problem, or just an idea. We learn by doing and sharing. We've all got something to contribute.

Comments / Reactions

One of the most enjoyable things about blogging is engaging with and learning from others. Leave a comment below with your questions, comments, or ideas. Let's start a conversation!