• 0

[.NET] Remove null items from ArrayList


Question

Don't ask why, but I am in a situation like this:

I have a set of objects in an ArrayList. At certan points in my program, I have to set some of the objects equal to null. Then, at another point in my program, I have to remove all those null items from the ArrayList. Here's a snippet of the code:

// Remove nulls for the new set
ArrayList removeIndex = new ArrayList();
for (int i = 0; i < Count; ++i)
{
	if (this[i] == null)
	{
  removeIndex.Add(i);
	}
}

for (int i = 0; i < removeIndex.Count; ++i)
{
	InnerList.RemoveAt(Convert.ToInt32(removeIndex[i]));
}

I have to have two for loops. One to find all the index values of null values, and the second to remove them (removing from an array you are looping through is a bad idea :D).

The problem is the RemoveAt statement. When I try to RemoveAt an index that is null, I get an ArgumentNull exception.

I don't see any other way around what I'm doing, besides a LOT of complicated math. Am I missing something, or is this impossible?

Link to comment
https://www.neowin.net/forum/topic/249626-net-remove-null-items-from-arraylist/
Share on other sites

1 answer to this question

Recommended Posts

  • 0

I knew I would figure it out. I replaced:

RemoveAt(Convert.ToInt32(removeIndex[i]));

with

InnerList.RemoveAt(Convert.ToInt32(removeIndex[i]));

(By the way, my class inherits CollectionBase).

The reason behind this is RemoveAt() calls the CollectionBase's implementation of RemoveAt, which is object based. InnerList.RemoveAt() call's the ArrayList implemention of RemoveAt, which is array (index) based.

Yay!

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.