A Shortcut for c# null and Any() checks

Often in C# I have to do this

if(x.Items!=null && x.Items.Any())
{ .... }

Is there a short cut on a collection ?

Jon Skeet
people
quotationmark

In C# 6, you'll be able to write:

if (x.Items?.Any() == true)

Before that, you could always write your own extensions method:

public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
    return source != null && source.Any();
}

Then just use:

if (x.NotNullOrEmpty())

Change the name to suit your tastes, e.g. NullSafeAny might be more to your liking - but I'd definitely make it clear in the name that it's a valid call even if x is null.

people

See more on this question at Stackoverflow