lolalola
lolalola

Reputation: 3823

Clear all array list data

Why doesn't the code below clear all array list data?

        Console.WriteLine("Before cleaning:" + Convert.ToString(ID.Count));
        //ID.Count = 20
        for (int i = 0; i < ID.Count; i++)
        {
            ID.RemoveAt(i);
        }
        Console.WriteLine("After cleaning:" + Convert.ToString(ID.Count));
        //ID.Count = 10

Why is 10 printed to the screen?

Maybe there is another special function, which deletes everything?

Upvotes: 10

Views: 21641

Answers (6)

Jon Skeet
Jon Skeet

Reputation: 1500055

You're only actually calling RemoveAt 10 times. When i reaches 10, ID.Count will be 10 as well. You could fix this by doing:

int count = ID.Count;
for (int i = 0; i < originalCount; i++)
{
    ID.RemoveAt(0);
}

This is an O(n2) operation though, as removing an entry from the start of the list involves copying everything else.

More efficiently (O(n)):

int count = ID.Count;
for (int i = 0; i < originalCount; i++)
{
    ID.RemoveAt(ID.Count - 1);
}

or equivalent but simpler:

while (ID.Count > 0)
{
    ID.RemoveAt(ID.Count - 1);
}

But using ID.Clear() is probably more efficient than all of these, even though it is also O(n).

Upvotes: 12

Johnny
Johnny

Reputation: 1575

`Array.Clear()` 

removes all items in the array.

`Array.RemoveAt(i)` 

removes the element of ith index in the array.

Upvotes: 10

Mike
Mike

Reputation: 3015

Your code does:

ID.RemoveAt(0);
...
ID.RemoveAt(9);
ID.RemoveAt(10); \\ at this point you have already removed 10 
                 \\ items so there is nothing left on 10- 19, but you are left with 
                 \\ the 'first' 10 elements
...
ID.RemoveAt(19);

Generally speaking your method removes every second element from the list..

Use ArrayList.Clear instead as other have mentioned.

Upvotes: 1

Amsakanna
Amsakanna

Reputation: 12934

Use the clear() Method

or

change ID.RemoveAt(i); to ID.RemoveAt(0);

Whenever an element is removed from the collection, its index also changes. Hence when you say ID.RemoveAt(0); the element at index 1 now will be moved to index 0. So again you've to remove the same element (like dequeuing). until you reach the last element. However if you want to remove all the elements at once you can better use the Clear() method.

Upvotes: 2

Oded
Oded

Reputation: 498942

After removing 10 items, ID.Count() == 10 and i == 10 so the loop stops.

Use ID.Clear() to remove all items in the array list.

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176896

ArrayList.Clear Method
Removes all elements from the ArrayList.

for more detail : http://msdn.microsoft.com/en-us/library/system.collections.arraylist.clear.aspx

Upvotes: 6

Related Questions