Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear all array list data

Tags:

c#

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?

like image 622
lolalola Avatar asked May 19 '10 06:05

lolalola


1 Answers

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).

like image 178
Jon Skeet Avatar answered Sep 29 '22 11:09

Jon Skeet