Removing alternate elements in a List

后端 未结 8 1100
执笔经年
执笔经年 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:51

    Just for consideration of a solution that creates a new list, with a list old you could do this:

    var newList = old.Where((_, i) => i%2 != 0).ToList();
    

    or, obviously

    var newList = l.Where((_, i) => i%2 == 0).ToList();
    

    depending which alternation you choose.

    EDIT

    The answer is quite a bit quicker. If you read something else here, it's because I measured on a weekend and weekend's brain is funny. :( The closure solution is about 40% quicker while the answer is app. 2 orders of magnitude faster. I suppose it will really depend how big your list becomes!

提交回复
热议问题