How to remove elements from an array

前端 未结 5 1162
闹比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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 08:59

    a couple of options:

    List indexesToRemove = new List();
    for(int i = results.Count; i >= 0; i--)
    {
      if(someCondition)
      {
         //results.Remove(results[i]);
           indexesToRemove.Add(i);
      }
    }
    
    foreach(int i in indexesToRemove) {
    results.Remove(results[i]);
    }
    

    or alternatively, you could make a copy of the existing list, and instead remove from the original list.

    //temp is a copy of results
    for(int i = temp.Count-1; i >= 0; i--)
    {
      if(someCondition)
      {
         results.Remove(results[i]);
      }
    }
    

提交回复
热议问题