The dilema

Sometimes you need to do some action to check if an element is not present in a collection, for example, check if a customer is in the Customers collection before trying to add it.

With .NET there are several ways to do so: For example if the collection is a List you can use Exists() or if you want to check the presence of the object itself, you can use Contains(). Using Linq, we can also do it with Any and All

In today’s article, we’re gonna find if it’s better to use !.Any() or .All()

The scenario

Let’s think of a customer list and a new customer I’m about to add, like this:

Collection<Customer> Customers = MyRepo.GetAllCustomers();
Customer myCustomer = CustomerMappedFromViewModel();

Before adding the new customer, I want to see if there is already another customer with the same Id in the collection, to avoid duplications. We can solve this with any of the two following options:

Using !Any to check that the customer Id is not present in any of the Customers list

if (!Customers.Any(cust => cust.Id == myCustomer.Id)) { 
    Customers.Add(myCustomer); 
}

Or using All to check that all the Customers.Id are different from the customer Id we want to add:

if (Customers.All(cust => cust.Id != myCustomer.Id)) { 
    Customers.Add(myCustomer); 
}

The trivia

Seeing this two options, what one do you think is best to use?

Most people would use the first one. Normally this happens because the words Any and All trick our mind to think that All will iterate “all” of the collection items to see if they’re different, while Any will stop looking when “any” of the items matches the predicate.

The reality, though, is another. Let’s go deeper in the matter.

Digging into .NET dark shadows

Using Reflector to see the Linq code for Any and All we can see this:

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (predicate == null)
    {
        throw Error.ArgumentNull("predicate");
    }
    foreach (TSource current in source)
    {
        if (predicate(current))
        {
            return true;
        }
    }
    return false;
}
public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (predicate == null)
    {
        throw Error.ArgumentNull("predicate");
    }
    foreach (TSource current in source)
    {
        if (!predicate(current))
        {
            return false;
        }
    }
    return true;
}

Surprise! Both implementations do EXACTLY the same. The only difference is that Any stops iterating when the predicate matches and returns true, while All stops iterating when the predicate doesn’t match, and returns false. So, the time that will take Any and All to do the job, will be almost the same (depending on the values).

Knowing this, we return again to square one: If they do almost the same, what one should I use?

And the winner is…

For best practices, the right option should be Option 2 (All)

if (Customers.All(cust => cust.Id != myCustomer.Id)) {
    Customers.Add(myCustomer); 
}

Following best practices, we should always make our “if” statements to check a positive predicate result instead of negating it. For example:

if (ThisHappens()) {
    DoThis();
}
else {
    DoThat();
}

Is correct, while this:

if (!ThisHappens()) {
    DoThat();
}
else {
    DoThis();
}

Is incorrect!

Under that circumstances, using .All in this case is better than using !.Any

Cheers and good coding!

Follow me

Joan Vilariño

Senior .NET Developer at Ohpen
Developer for more than 25 years and IT, gadget, mobile and electronics enthusiast working and publishing from Barcelona.
Follow me