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)
{
results.Remove(results[i]);
}
}
To me it seems like bad practice to be removing the elements while still iterating through the loop because you’ll be modifying the indexes.
Is this a correct assumption?
Is there a better way of doing this? I would like to use LINQ but I’m in 2.0 Framework
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 atresults.Count -1since array indexes start at 0.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
Lengthproperty (instead of aCountproperty) 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
MyTypewith the actual type you are dealing with: