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.
Method details. 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.
Input and output. 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"
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.
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
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.