Caspar Kleijne Caspar Kleijne - 1 month ago 7
C# Question

What is the opposite method of Any<T>

How can I check with Linq if a collection does not contain an object. I.E. The opposite of

Any<T>
.

I could invert the result with a
!
but for readability I wondered if there was a more better way to do this? Should I add the extension myself?

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);
}
Comments