Sometimes we want to only get alternating, or every Nth element, from a list. We do not want every element. With a special method this is possible.
By using modulo, we can test the indexes of each element. Then we add elements with matching indexes to a second list. The second list is then returned.
Consider a C# List
that has 4 elements: the lowercase 1-chars strings from "abcd." When we get every second element, we should have "a" and "c."
List<string>: "a", "b", "c", "d" Nth(2): "a", "c"
We introduce a special method called EveryNthElement
. This method receives 2 parameters—the list we want elements from, and the "N" from Nth.
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)); } }a,c,e,g,i a,d,g
To establish the correct behavior of an Nth element method, I checked the Nth child selector in CSS. This can be used in any modern web browser.
EveryNthElement
result is correct here.Many improvements could be made to this Nth element method. We could add an adjustment argument to the starting index. We could use a generic type for the list element type.