DEV Community

Rafael Câmara
Rafael Câmara

Posted on

C# LINQ Any Explained

The Any LINQ method allows you to check if there are elements in a given collection that satisfy a given condition. If at least one element satisfies the condition, true is returned. Otherwise, false.

If you provide no condition to check against the collection's elements, the Any LINQ method will check if the collection has any elements. If elements are present in the collection, the method will return true. Otherwise, false.

Let's assume we have the following list of numbers: [1, 2, 3, 4, 5], and you want to check if there are numbers that are greater than 3.

In this case, we do have 4 and 5:

list that contains numbers 1, 2, 3, 4, and 5 and highlights 4 and 5

Since we have at least one element that satisfies the condition, the Any method will return true.

If we change the condition to check if any elements are greater than 10, the outcome would be false.

Any in code

Let's first start by creating our sample collection:

public static int[] SimpleCollection = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Let's test the first scenario, which checks if any elements are greater than 3.

var isBiggerThan3 = SimpleCollection.Any(number => number > 3);
Enter fullscreen mode Exit fullscreen mode

Notice the condition number => number > 3. It's passed as a lambda expression to the Any method and will be tested against the elements of the collection.

The variable isBiggerThan3 would hold the value of true.

In the second scenario, we would have to adjust our code to something similar to this:

var isBiggerThan10 = SimpleCollection.Any(number => number > 10);
Enter fullscreen mode Exit fullscreen mode

The variable isBiggerThan10 would hold the value of false.

Resources

If you are more of a visual learner, I’ve created a playlist showcasing the Any LINQ method and other ones.

If you want to go directly to the Any videos, here are the direct links for the theory and practice.

Here you can find a variation of the source code presented in this article.

Top comments (0)