What is the most efficient way to remove alternate (odd indexed or even indexed) elements in an List
without using a place holder list variable?
A
If you call RemoveAt for every item you remove, you will be moving a lot of data. The most efficient is to move the items together that you want to keep, then remove the unused items at the end:
int pos = 0;
for (int i = 0; i < values.Count; i += 2, pos++) {
values[pos] = values[i];
}
values.RemoveRange(pos, values.Count - pos);
Edit:
This method will process a list of a million ints in 15 ms. Using RemoveAt it will take over three minutes...
Edit2:
You could actually start with pos=1 and i=2 (or 3), as the first item doesn't have to be copied to itself. This makes the code a bit less obvious though.