How to remove elements from an array

前端 未结 5 1201
闹比i
闹比i 2021-01-15 08:22

Hi I\'m working on some legacy code that goes something along the lines of

for(int i = results.Count-1; i >= 0; i--)
{
  if(someCondition)
  {
     result         


        
5条回答
  •  长情又很酷
    2021-01-15 08:56

    The removal is actually ok since you are going downwards to zero, only the indexes that you already passed will be modified. This code actually would break for another reason: It starts with results.Count, but should start at results.Count -1 since array indexes start at 0.

    for(int i = results.Count-1; i >= 0; i--)
    {
      if(someCondition)
      {
         results.RemoveAt(i);
      }
    }
    

    Edit:

    As was pointed out - you actually must be dealing with a List of some sort in your pseudo-code. In this case they are conceptually the same (since Lists use an Array internally) but if you use an array you have a Length property (instead of a Count property) and you can not add or remove items.

    Using a list the solution above is certainly concise but might not be easy to understand for someone that has to maintain the code (i.e. especially iterating through the list backwards) - an alternative solution could be to first identify the items to remove, then in a second pass removing those items.

    Just substitute MyType with the actual type you are dealing with:

    List removeItems = new List();
    
    foreach(MyType item in results)
    {
       if(someCondition)
       {
            removeItems.Add(item);
       }
    }
    
    foreach (MyType item in removeItems)
        results.Remove(item);
    

提交回复
热议问题