Export (0) Print
Expand All

List(Of T).Insert Method

Inserts an element into the List(Of T) at the specified index.

Namespace:  System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Public Sub Insert ( _
	index As Integer, _
	item As T _
)

Parameters

index
Type: System.Int32

The zero-based index at which item should be inserted.

item
Type: T

The object to insert. The value can be Nothing for reference types.

Implements

IList(Of T).Insert(Int32, T)

ExceptionCondition
ArgumentOutOfRangeException

index is less than 0.

-or-

index is greater than Count.

List(Of T) accepts Nothing as a valid value for reference types and allows duplicate elements.

If Count already equals Capacity, the capacity of the List(Of T) is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.

If index is equal to Count, item is added to the end of List(Of T).

This method is an O(n) operation, where n is Count.

The following example demonstrates how to add, remove, and insert a simple business object in a List(Of T).

Imports System.Collections.Generic
' Simple business object. A PartId is used to identify the type of part  
' but the part name can change.  
Public Class Part
    Implements IEquatable(Of Part)
    Public Property PartName() As String 
        Get 
            Return m_PartName
        End Get 
        Set(value As String)
            m_PartName = Value
        End Set 
    End Property 
    Private m_PartName As String 

    Public Property PartId() As Integer 
        Get 
            Return m_PartId
        End Get 
        Set(value As Integer)
            m_PartId = Value
        End Set 
    End Property 
    Private m_PartId As Integer 

    Public Overrides Function ToString() As String 
        Return "ID: " & PartId & "   Name: " & PartName
    End Function 
    Public Overrides Function Equals(obj As Object) As Boolean 
        If obj Is Nothing Then 
            Return False 
        End If 
        Dim objAsPart As Part = TryCast(obj, Part)
        If objAsPart Is Nothing Then 
            Return False 
        Else 
            Return Equals(objAsPart)
        End If 
    End Function 
    Public Overrides Function GetHashCode() As Integer 
        Return PartId
    End Function 
    Public Overloads Function Equals(other As Part) As Boolean _
        Implements IEquatable(Of Part).Equals
        If other Is Nothing Then 
            Return False 
        End If 
        Return (Me.PartId.Equals(other.PartId))
    End Function 
    ' Should also override == and != operators. 

End Class 
Public Class Example
    Public Shared Sub Main()
        ' Create a list of parts. 
        Dim parts As New List(Of Part)()

        ' Add parts to the list.
        parts.Add(New Part() With { _
             .PartName = "crank arm", _
             .PartId = 1234 _
        })
        parts.Add(New Part() With { _
             .PartName = "chain ring", _
             .PartId = 1334 _
        })
        parts.Add(New Part() With { _
             .PartName = "regular seat", _
             .PartId = 1434 _
        })
        parts.Add(New Part() With { _
             .PartName = "banana seat", _
             .PartId = 1444 _
        })
        parts.Add(New Part() With { _
             .PartName = "cassette", _
             .PartId = 1534 _
        })
        parts.Add(New Part() With { _
             .PartName = "shift lever", _
             .PartId = 1634 _
        })



        ' Write out the parts in the list. This will call the overridden ToString method 
        ' in the Part class.
        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next 


        ' Check the list for part #1734. This calls the IEquitable.Equals method 
        ' of the Part class, which checks the PartId for equality.
        Console.WriteLine(vbLf & "Contains(""1734""): {0}", parts.Contains(New Part() With { _
             .PartId = 1734, _
             .PartName = "" _
        }))

        ' Insert a new item at position 2.
        Console.WriteLine(vbLf & "Insert(2, ""1834"")")
        parts.Insert(2, New Part() With { _
             .PartName = "brake lever", _
             .PartId = 1834 _
        })


        'Console.WriteLine(); 
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

        Console.WriteLine(vbLf & "Parts[3]: {0}", parts(3))

        Console.WriteLine(vbLf & "Remove(""1534"")")

        ' This will remove part 1534 even though the PartName is different, 
        ' because the Equals method only checks PartId for equality.
        parts.Remove(New Part() With { _
             .PartId = 1534, _
             .PartName = "cogs" _
        })

        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

        Console.WriteLine(vbLf & "RemoveAt(3)")
        ' This will remove part at index 3.
        parts.RemoveAt(3)

        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next 
    End Sub 
    
    '        This example code produces the following output: 
    '        ID: 1234   Name: crank arm 
    '        ID: 1334   Name: chain ring 
    '        ID: 1434   Name: regular seat 
    '        ID: 1444   Name: banana seat 
    '        ID: 1534   Name: cassette 
    '        ID: 1634   Name: shift lever 
    
    '        Contains("1734"): False 
    
    '        Insert(2, "1834") 
    '        ID: 1234   Name: crank arm 
    '        ID: 1334   Name: chain ring 
    '        ID: 1834   Name: brake lever 
    '        ID: 1434   Name: regular seat 
    '        ID: 1444   Name: banana seat 
    '        ID: 1534   Name: cassette 
    '        ID: 1634   Name: shift lever 
    
    '        Parts[3]: ID: 1434   Name: regular seat 
    
    '        Remove("1534") 
    
    '        ID: 1234   Name: crank arm 
    '        ID: 1334   Name: chain ring 
    '        ID: 1834   Name: brake lever 
    '        ID: 1434   Name: regular seat 
    '        ID: 1444   Name: banana seat 
    '        ID: 1634   Name: shift lever 
    '   ' 
    '        RemoveAt(3) 
    
    '        ID: 1234   Name: crank arm 
    '        ID: 1334   Name: chain ring 
    '        ID: 1834   Name: brake lever 
    '        ID: 1444   Name: banana seat 
    '        ID: 1634   Name: shift lever 
    '         

End Class

The following example demonstrates the Insert method, along with various other properties and methods of the List(Of T) generic class. After the list is created, elements are added. The Insert method is used to insert an item into the middle of the list. The item inserted is a duplicate, which is later removed using the Remove method.

Imports System
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()
        Dim dinosaurs As New List(Of String)

        Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)

        dinosaurs.Add("Tyrannosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")
        dinosaurs.Add("Compsognathus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)
        Console.WriteLine("Count: {0}", dinosaurs.Count)

        Console.WriteLine(vbLf & "Contains(""Deinonychus""): {0}", _
            dinosaurs.Contains("Deinonychus"))

        Console.WriteLine(vbLf & "Insert(2, ""Compsognathus"")")
        dinosaurs.Insert(2, "Compsognathus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next 
        ' Shows how to access the list using the Item property.
        Console.WriteLine(vbLf & "dinosaurs(3): {0}", dinosaurs(3))
        Console.WriteLine(vbLf & "Remove(""Compsognathus"")")
        dinosaurs.Remove("Compsognathus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        dinosaurs.TrimExcess()
        Console.WriteLine(vbLf & "TrimExcess()")
        Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)
        Console.WriteLine("Count: {0}", dinosaurs.Count)

        dinosaurs.Clear()
        Console.WriteLine(vbLf & "Clear()")
        Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)
        Console.WriteLine("Count: {0}", dinosaurs.Count)
    End Sub 
End Class 

' This code example produces the following output: 

'Capacity: 0 

'Tyrannosaurus 
'Amargasaurus 
'Mamenchisaurus 
'Deinonychus 
'Compsognathus 

'Capacity: 8 
'Count: 5 

'Contains("Deinonychus"): True 

'Insert(2, "Compsognathus") 

'Tyrannosaurus 
'Amargasaurus 
'Compsognathus 
'Mamenchisaurus 
'Deinonychus 
'Compsognathus 

'dinosaurs(3): Mamenchisaurus 

'Remove("Compsognathus") 

'Tyrannosaurus 
'Amargasaurus 
'Mamenchisaurus 
'Deinonychus 
'Compsognathus 

'TrimExcess() 
'Capacity: 5 
'Count: 5 

'Clear() 
'Capacity: 5 
'Count: 0

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft