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.
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.
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.
List
. It is important that we can access the indexes, as we test them.if
-statement with the Mod
keyword to determine if the element index is evenly divisible by our "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 Modulea,c,e,g,i a,d,g
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.
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.