score:94

Accepted answer

You can easily create a None extension method:

public static bool None<TSource>(this IEnumerable<TSource> source)
{
    return !source.Any();
}

public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    return !source.Any(predicate);
}

score:2

In addition to the answers added, if you don't want to wrap Any() method you can implement None() as follows:

public static bool None<TSource>(this IEnumerable<TSource> source) 
{
    if (source == null) { throw new ArgumentNullException(nameof(source)); }

    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        return !enumerator.MoveNext();
    }
}

public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null) { throw new ArgumentNullException(nameof(source)); }
    if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); }

    foreach (TSource item in source)
    {
        if (predicate(item))
        {
            return false;
        }
    }

    return true;
}

In addition to that for the parameterless overload you can apply ICollection<T> optimization, which actually does not exist in LINQ implemenetation.

ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null) { return collection.Count == 0; }

score:4

Found this thread when I wanted to find out if a collection does not contain one object but I do not want to check that all objects in a collection match the given criteria. I ended up doing a check like this:

var exists = modifiedCustomers.Any(x => x.Key == item.Key);

if (!exists)
{
    continue;
}

score:75

The opposite of verifying that any (at least one) record matches a certain criteria would be verifying that all records do not match the criteria.

You didn't post your full example, but if you wanted the opposite of something like:

var isJohnFound = MyRecords.Any(x => x.FirstName == "John");

You could use:

var isJohnNotFound = MyRecords.All(x => x.FirstName != "John");

Related Query

More Query from same tag