Removing alternate elements in a List

后端 未结 8 1102
执笔经年
执笔经年 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条回答
  •  抹茶落季
    2021-02-12 18:53

    I'm not sure what you mean by alternate but if you mean "every other item" the following code will work. It will start by removing the 2nd element, then the 4th, and so on

    List list = GetTheList();
    int i = 1;
    while ( i < list.Count ) {
      list.RemoveAt(i);
      i++;
    }
    

提交回复
热议问题