How do I select every 6th element from a list (using Linq)
There is an overload of the Where method with lets you use the index directly:
coordinateRange.Where((c,i) => (i + 1) % 6 == 0);
coordinateRange.Where( ( coordinate, index ) => (index + 1) % 6 == 0 );
The answer from Webleeuw was posted prior to this one, but IMHO it's clearer to use the index as an argument instead of using the IndexOf
method.
Something like this could help:
public static IEnumerable<T> Every<T>(this IEnumerable<T> source, int count)
{
int cnt = 0;
foreach(T item in source)
{
cnt++;
if (cnt == count)
{
cnt = 0;
yield return item;
}
}
}
You can use it like this:
int[] list = new []{1,2,3,4,5,6,7,8,9,10,11,12,13};
foreach(int i in list.Every(3))
{ Console.WriteLine(i); }
EDIT:
If you want to skip the first few entries, you can use the Skip() extension method:
foreach (int i in list.Skip(2).Every(6))
{ Console.WriteLine(i); }
Any particular reason you want to use LINQ to do this?
Why not write a loop that steps with 6 increments each time and get access the value directly?