Insert Items To List Using VB.NET

In this article I describe how to add items in list at the specified position.
  • 3978

Insert Items

The Insert method inserts an item to a List at the specified position. The following code snippet creates a List and inserts an item to the List by using the Insert method.

' Create a list

Dim AuthorList As New List(Of String)()

' Add items using Add method

AuthorList.Add("Mahesh Chand")

AuthorList.Add("Praveen Kumar")

AuthorList.Add("Raj Kumar")

AuthorList.Add("Nipun Tomar")

AuthorList.Add("Dinesh Beniwal")

' Insert an item at position 2

AuthorList.Insert(1, "Second Author")

The AddRange method is used to add a collection of items. The following code snippet adds a collection of items to a List.

' Insert a range of items

Dim authors As String() = {"Mike Gold", "Don Box", "Sundar Lal", "Neel Beniwal"}

AuthorList.InsertRange(4, authors)
 

Here is the complete Code:
 

Imports System.Text

Imports System.IO

Imports System.Collections.Generic

Module Module1

    Sub Main()

        ' Create a list

        Dim AuthorList As New List(Of String)()

        ' Add items using Add method

        AuthorList.Add("Mahesh Chand")

        AuthorList.Add("Praveen Kumar")

        AuthorList.Add("Raj Kumar")

        AuthorList.Add("Nipun Tomar")

        AuthorList.Add("Dinesh Beniwal")

        ' Insert an item at position 2

        AuthorList.Insert(1, "Second Author")

        ' Insert a range of items

        Dim authors As String() = {"Mike Gold", "Don Box", "Sundar Lal", "Neel Beniwal"}

        AuthorList.InsertRange(4, authors)

        For Each author In AuthorList

            Console.WriteLine(author)

        Next

        Console.ReadLine()

    End Sub

End Module

Output:

 insert-items-in-list-vb.net.jpg

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.