In this article, we will explore the differences between Any() and Exists() methods in C#. 

Although at first glance they might seem similar, they possess distinct characteristics and we use them in different scenarios in order to manipulate data collections.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Understanding the Any Method in C#

The LINQ Any() method allows us to determine if any element of a collection exists or satisfies a given condition. It does this by traversing the collection, checking the elements one by one, and returning a boolean value whenever the result can be determined. Moreover, we can use it with all collections that implement the IEnumerable<T> interface such as Arrays, Lists, Dictionaries, etc. 

It is important to note that if the collection we invoke this method on is null, it will throw ArgumentNullException. 

There are two overloads of the Any() method, the first one doesn’t require any additional parameters and simply checks if the source is empty or not:

public static bool Any<TSource> (this IEnumerable<TSource> source);

The second one takes a generic delegate as a parameter and can determine if the collection is empty and if at least one element satisfies the given condition or not:

public static bool Any<TSource> (this IEnumerable<TSource> source, Func<TSource,bool> predicate);

Now that we have a general sense of how the Any() method works, let’s look at an example of how we can use it in our code:

public static class NumbersHelper
{
    public static bool CheckIfArrayIsEmpty(int[] numbers) 
        => !numbers.Any();

    public static bool CheckIfListContainsPositiveNumbersAny(List<int> numbers) 
        => numbers.Any(x => x > 0);
}

The NumbersHelper class includes two methods that query a collection of integers. The CheckIfArrayIsEmpty() method uses the first overload to check if an array of integers is empty. The CheckIfListContainsPositiveNumbersAny() method uses the second overload to check if a list of integers contains any positive numbers by using the x => x > 0 lambda expression.

We can learn more about the Any() method here.

Understanding the Exists Method in C#

The Exists() method determines if the collection contains elements that match the conditions defined by the specified predicate. The search stops as soon as the result can be determined and a corresponding boolean value is returned. The main difference between these two methods is that we can apply the Exists() method to List<T> collections only.

Similarly to Any(), it does not handle null collections and throws ArgumentNullException.

It has only one overload which takes a predicate delegate as an argument and determines if any elements satisfy the conditions:

public bool Exists (Predicate<T> match);

This time we will see an example of the Exists() method to understand its usage in real-world scenarios:

public static class NumbersHelper
{
    public static bool CheckIfListContainsPositiveNumbersExists(List<int> numbers)
        => numbers.Exists(x => x > 0);
}

In the code above we added the CheckIfListContainsPositiveNumbersExists()method to the NumbersHelper class. This method utilizes the Exists() method to check if positive numbers exist in a list of integers. We did that by utilizing the x => x > 0 expression.

For more information about the Exists() method check here.

Comparison Between Any and Exists Methods

Now that we have a brief overview of Any() and Exists(), let’s compare them:

AnyExists
Part of LINQ, introduced in .NET 3.5Part of the System.Collections.Generic namespace, introduced in .NET Framework 2.0
Can be used with any collection that implements the IEnumerable interfaceCan be used with List collections
Meant to be used with lambda expressions and LINQMeant to be used with predicate delegate but can be used with lambda as well (backward compatible)
Can check if the collection is empty or notCannot check if the List is empty
Can check if the collection contains elements that satisfy a conditionCan check if the List contains elements that satisfy a condition
Stops as soon as the result can be determinedStops as soon as the result can be determined
Worse performance when used with Lists (check section below)Better performance when used with Lists

Performance

For comparison of these two methods in terms of performance, we will run benchmarks for the CheckIfListContainsPositiveNumbersAny() and CheckIfListContainsPositiveNumbersExists() methods with lists of 10.000, 100.000, and 1.000.000 objects:

|                              Method | ListSize |        Mean |     Error |    StdDev | Allocated |
|------------------------------------ |--------- |------------:|----------:|----------:|----------:|
| ComparePositiveNumbersMethodsExists |    10000 |    20.17 us |  0.057 us |  0.054 us |         - |
|    ComparePositiveNumbersMethodsAny |    10000 |    83.70 us |  0.961 us |  0.802 us |      40 B |
| ComparePositiveNumbersMethodsExists |   100000 |   201.18 us |  0.143 us |  0.112 us |         - |
|    ComparePositiveNumbersMethodsAny |   100000 |   813.19 us |  4.191 us |  3.715 us |      40 B |
| ComparePositiveNumbersMethodsExists |  1000000 | 2,022.05 us |  7.193 us |  6.728 us |       2 B |
|    ComparePositiveNumbersMethodsAny |  1000000 | 8,128.84 us | 40.149 us | 35.591 us |      48 B |

As we can notice there is a big performance difference, both in execution time and memory allocation, in favor of Exists() over Any() when used with a List<T>. Keep in mind though that this is a simple example and there are a lot of variables that can affect the performance of these methods and those results can be much faster. 

When to Choose Between Any and Exists

At this point after analyzing the main differences let’s see the use cases for Any() and Exists() methods.

The Any() method is more versatile as it is compatible with any collection that implements the IEnumerable interface. Furthermore, it can check for the emptiness of a collection as well as for elements that satisfy a condition. 

On the other hand, the Exists() method is specifically designed for List collections. It serves a narrower purpose, exclusively allowing us to check if any elements within the list satisfy a given condition. Furthermore, when using List collections, Exists() offers better performance.

Conclusion

In summary, in this article, we discussed Any() and Exists() in C#. These methods help us query collections and determine if at least one of their elements satisfies a condition. Firstly we saw their properties and provided a simple example for each one. After that, we compared the two of them by providing their differences and similarities in terms of usability, syntax, and performance. Last but not least we analyzed the cases in which we can best use each method.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!