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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With