Removing alternate elements in a List

后端 未结 8 1094
执笔经年
执笔经年 2021-02-12 18:41

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

8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 18:57

    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.

提交回复
热议问题