C's method of iterating over List and deleting an element

  • 2020-12-22 17:45:21
  • OfStack

This article takes an example of how C# traverses List and removes an element. Share to everybody for everybody reference. The details are as follows:

1. We choose for loop:


for(int i=0;i<list.count;i++)
{
   if(list[i])
  {
    list.RemoveAt(i);
  }
}

If I go around like this, it's not right,
{A B C E F G H} Assume the current traversal to D (i=3), remove, and then traverse to i=4(F), skipping E (i=3)

2. We use reverse traversal, and this problem is solved


for(int i=list.Count-1;i>=0;i--)
{
   if(list[i])
  {
    list.RemoveAt(i);
  }
}

Hopefully this article has helped you with your C# programming.


Related articles: