Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return zero for Count() on null IEnumerables

I'm getting tired of using code like this:

var count = 0;
if (myEnumerable != null)
{
    count = myEnumerable.Count();
}

And this is a bit pedantic:

var count = (myEnumerable ?? new string[0]).Count();

Is there any tidier way of doing this? I once had a (badly named) PhantomCount extension method on IEnumerable<> that used my first code example, but it had something of a smell about it (besides the name).

like image 926
ProfK Avatar asked Aug 19 '10 08:08

ProfK


4 Answers

The problem is really in whatever is creating these enumerables. Unless you have a really good reason, anything that generates an iterable collection should return an empty collection instead of null. This would align with the Null-Object-Pattern, hence the benefits are the same.

My suggestion would be to fix whatever produces myEnumerable, or if you can't do this, add a check way earlier to see if it's null and react appropriately.

like image 69
Anon. Avatar answered Nov 07 '22 12:11

Anon.


How about

count = myEnumerable == null? 0 : myEnumerable.Count()
like image 24
cordialgerm Avatar answered Nov 07 '22 12:11

cordialgerm


I don't think using extension method is a bad idea.

public static int NullableCount<T>(this IEnumerable<T> collection)
{
   return collection == null ? 0 : collection.Count();
}
like image 10
Cheng Chen Avatar answered Nov 07 '22 11:11

Cheng Chen


I use a custom extension method:

public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();
}

...

int count = myEnumerable.EmptyIfNull().Count();
like image 6
Thomas Levesque Avatar answered Nov 07 '22 13:11

Thomas Levesque