Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing All Nulls From Collections

I'm having to deal with collections of data being thrown at my application from data sources out of my control. Some of these collections contain nulls which I would prefer to filter out as soon as they hit my code rather than scatter null checking code all over the place. I want to do this in a reusable generic fashion and have written this method to do it:

    public static void RemoveNulls<T>(this IList<T> collection) where T : class
    {
        for (var i = 0; i < collection.Count(); i++)
        {
            if (collection[i] == null)
                collection.RemoveAt(i);
        }
    }

I know on the concrete List class there is the RemoveAll() method that could be used like:

collection.RemoveAll(x => x == null);

But a lot of the return types are interface based (IList/ IList ...) rather than concrete types.

like image 267
Jammer Avatar asked Nov 29 '22 08:11

Jammer


2 Answers

Instead of removing nulls from source collection, you can create a copy of collection without nulls using LINQ:

collection.Where(i => i != null).ToList();

Extension methods would work on any IEnumerable, including IList.

like image 164
alex Avatar answered Dec 12 '22 23:12

alex


Your method won't work because removing an element will cause the index of all subsequent elements to be decremented. If you don't want a Linq solution (which seems simplest: see the answer from @alex), you should iterate backwards.

public static void RemoveNulls<T>(this IList<T> collection) where T : class
{
    for (var i = collection.Count-1; i >= 0 ; i--)
    {
        if (collection[i] == null)
            collection.RemoveAt(i);
    }
}
like image 35
Joe Avatar answered Dec 12 '22 22:12

Joe