score:5

Accepted answer

enumerable.select has an overload that projects the current index of the element in the sequence. also enumerable.where and enumerable.skipwhile/takewhile have it. you can use it like a loop variable in a for-loop which is sometimes handy.

one example which uses the index to create an anonymous type to group a long list into groups of 4:

var list = enumerable.range(1, 1000).tolist();

list<list<int>> groupsof4 = list
    .select((num, index) => new { num, index })
    .groupby(x => x.index / 4).select(g => g.select(x => x.num).tolist())
    .tolist();  // 250 groups of 4

or one with where which only selects even indices:

var evenindices = list.where((num, index) => index % 2 == 0);

it might also be important to mention that you can use these overloads that project the index only in method-syntax. linq query-syntax does not support it.


Related Query

More Query from same tag