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
The way to Nirvana is paved with deferred execution. Or something.
public static IEnumerable AlternateItems(this IEnumerable source)
{
while (source.Any())
{
yield return source.First();
source = source.Skip(1);
if (source.Any()) source = source.Skip(1);
}
}
This works for all sequences, not just IList<>
. The cost of iteration is deferred until iteration, which may be a big win if, in the end, you don't need to touch all the elements in the list.
In my simple tests, the performance when you iterate over the whole list is not very good, so be sure to profile your real situation.