Home
Map
List Every Nth ElementGet every nth element from a List and place the elements in a new List.
VB.NET
This page was last reviewed on Aug 8, 2023.
Nth element. In VB.NET we often use Lists of elements. Sometimes it can be useful to generate a List of every Nth element from our Lists.
List
With some modulo logic, we can test for every second element, third element or other distance. The Mod keyword, which is modulo division in VB.NET can be used here.
Mod
Example. We introduce a function EveryNthElement, which receives a List of strings, and returns another List of strings. The result is a collection containing the specified elements.
Step 1 We loop over all the indexes in the input List. It is important that we can access the indexes, as we test them.
For
Step 2 Here we use an if-statement with the Mod keyword to determine if the element index is evenly divisible by our "n" value.
If Then
Step 3 We return the list, which now contains all the elements at indexes that were evenly divisible by the "n" value.
Module Module1 Function EveryNthElement(list As List(Of String), n As Integer) As List(Of String) Dim result = New List(Of String) ' Step 1: loop over all indexes. For i As Integer = 0 To list.Count - 1 ' Step 2: use a modulo expression, and add values if the result is 0. If i Mod n = 0 result.Add(list(i)) End If Next ' Step 3: return the list. Return result End Function Sub Main() ' Use the function on this list. Dim test = New List(Of String)({ "a", "b", "c", "d", "e", "f", "g", "h", "i" }) Dim result = EveryNthElement(test, 2) Console.WriteLine(string.Join(",", result)) Dim result2 = EveryNthElement(test, 3) Console.WriteLine(string.Join(",", result2)) End Sub End Module
a,c,e,g,i a,d,g
Results. It is easy to determine that the function has correct output on the values 2 and 3. With 2, we skip over every other element. And with 3, we skip over 2 elements at a time.
A summary. Using modulo division (with the Mod keyword in VB.NET) allows us to test indexes with a distance between them. This allows us to sample all values separated with a specified distance.
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.
This page was last updated on Aug 8, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.