AB Kolan AB Kolan - 1 month ago 8
C# Question

Removing alternate elements in a List<T>

What is the most efficient way to remove alternate (odd indexed or even indexed) elements in an

List<T>
without using a place holder list variable?

Also it would be appreciated if you could mention the cost with each of your answer.

I'm looking for an efficient way to do this

Thanks in advance

Answer

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.