HomeSearch

C# Get Every Nth Element From List (Modulo)

Get every Nth element from a list using a modulo expression. Put the elements in a new list.
Nth element. 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.
An example program. Consider this example. We introduce a special method called EveryNthElement. This method receives 2 parameters—the list we want elements from, and the "N" from Nth.List

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.

Modulo
C# 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
Some notes, testing. 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.

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
A review. 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.Generic Class, Method
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.