I would like to remove elements from a list at once. Not in a loop.
Currently I am passing a from index number as a starting number and then removing it in a loop which is causing a lot of problems. Is there a way to remove all at once?
Basically remove from index 3 till the end.
public List<string> steps = new List<string> (); //Total count 10
public int fromIndex; //index is 3
void Start(){
int tempTrackNumber = fromIndex;
for(int i = tempTrackNumber; i < steps.Count; tempTrackNumber++) {
steps.Remove(steps[i]);
}
}
>Solution :
If the goal is to remove elements from index X to the end of the list then the goal is also to keep only the first X-1 elements, which can be done with .Take():
steps = steps.Take(fromIndex - 1).ToList();
Semantically you can then clarify the meaning of fromIndex to something like keepCount:
steps = steps.Take(keepCount).ToList();
(Adjusting for the off-by-one calculation when setting that value, of course.)