Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,752 questions

55,516 answers

573 users

How to remove every N‑th element from a list in VB.NET

1 Answer

0 votes
' ------------------------------------------------------------
' A small program demonstrating how to remove every Nth element
' from a List(Of T) using clear, expressive VB.NET patterns.
' ------------------------------------------------------------

Imports System
Imports System.Collections.Generic

Module Program
	'
	' This function returns a new list with every Nth element removed.
	'
	' It performs a single pass over the input list. VB.NET lists use
	' zero‑based indexing, so we check (index + 1) Mod n <> 0 to keep
	' elements that are *not* in the Nth position.
	'
	' The variable "size" captures the list length before the loop,
	' which avoids repeatedly accessing items.Count inside the loop.
	'
	Function RemoveEveryNth(Of T)(items As List(Of T), n As Integer) As List(Of T)
		If n <= 0 Then
			Throw New ArgumentException("n must be a positive integer")
		End If

		Dim result As New List(Of T)(items.Count)
		Dim size As Integer = items.Count   ' capture size once

		For i As Integer = 0 To size - 1
			If (i + 1) Mod n <> 0 Then
				result.Add(items(i))
			End If
		Next

		Return result
	End Function
	'
	' Keeping Main small and focused makes the program easy to extend.
	' Here we demonstrate the function with a simple example.
	'
	Sub Main()
        Dim data As New List(Of Integer)
        For i As Integer = 1 To 20
            data.Add(i)   ' Example list: numbers 1–20
        Next

        Dim n As Integer = 3   ' Remove every 3rd element

        Dim cleaned As List(Of Integer) = RemoveEveryNth(data, n)

        Console.WriteLine("Original: " & String.Join(" ", data))
        Console.WriteLine("After removing every " & n & "-th element: " &
                          String.Join(" ", cleaned))
    End Sub
End Module


'
' run:
'
' Original: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
' After removing every 3-th element: 1 2 4 5 7 8 10 11 13 14 16 17 19 20
'

 



answered 1 day ago by avibootz
...