C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Modulo: We use modulo division on the index (i) for each element in the list. When the result is 0, we have a valid result.
ModuloC# program that uses modulo with list indexes
using System;
using System.Collections.Generic;
class Program
{
static List<string> EveryNthElement(List<string> list, int n)
{
List<string> result = new List<string>();
for (int i = 0; i < list.Count; i++)
{
// Use a modulo expression.
if ((i % n) == 0)
{
result.Add(list[i]);
}
}
return result;
}
static void Main()
{
var test = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
// Skip over 2, then take 1, then skip over 2.
var result = EveryNthElement(test, 2); // want a,c,e,g,i
Console.WriteLine(string.Join(",", result));
// Skip over 3, then take 1.
var result2 = EveryNthElement(test, 3); // want a,d,g
Console.WriteLine(string.Join(",", result2));
}
}
Output
a,c,e,g,i
a,d,g
And: When the N is 2, we should select the first, third, and fifth elements. So the EveryNthElement result is correct here.
Nth-child: mozilla.org