Visual Basic Sorted List

In visual basic, SortedList is a generic type of collection and it is useful to store a collection of key/value pairs that are sorted by key based on the associated IComparer(Of T) implementation.

 

By default, the sorted list will sort a key/value pairs in ascending order of the key and the sorted list will allow storing only the strongly-typed objects i.e. the key/value pairs of the specified data type.

 

In visual basic, the sorted list will allow us to store duplicate values but the keys must be unique and cannot be null to identify the values in sortedlist and the size of sorted list will vary dynamically so we can add or remove elements from the sorted list based on our application requirements.

Visual Basic SortedList Declaration

In visual basic, sorted list is a generic type of collection and it is provided by System.Collections.Generic namespace.

 

As discussed, the collection is a class so to define a sorted list, we must need to declare an instance of the sortedlist class before we perform any operations like add, delete, etc. like as shown below.

 

Dim slist As SortedList(Of TKey, TValue) = New SortedList(Of TKeyTValue)()

If you observe the above sortedlist declaration, we created generic sortedlist (slst) with an instance of sortedlist class using type parameters (TKey, TValue) as placeholders within brackets.

 

Here, the brackets (Of TKey, Tvalue) will indicate that the sortedlist is generic type and type parameter TKey is to represent the type of keys to be accepted by sortedlist and TValue is used to represent the type of values to be accepted by sortedlist.

Visual Basic SortedList Initialization

Following is the example of initializing a generic sortedlist by specifying the required type for key and value.

 

Dim slist As SortedList(Of StringInteger) = New SortedList(Of StringInteger)()

If you observe the above example, we defined a sortedlist (slist) with the required key and value types to store. Here, the sortedlist will store a key of string type and value of int type.

 

Internally, the sortedlist will maintain a two object[] arrays, one for keys and another one for values so when we add key/value pair, it will perform a binary search using the key to find an appropriate index to store a key and value in respective arrays.

Visual Basic SortedList Properties

Following are the some of commonly used properties of generic sortedlist in visual basic programming language.

 

PropertyDescription
Capacity It is used to get or set the number of elements a sortedlist can contain.
Count It is used to get the number of key/value pair elements in list.
Item[TKey] It is used get or set the value associated with the specified key.
Keys It is used get a collection of keys in sortedlist.
Values It is used get a collection of values in sortedlist.

Visual Basic SortedList Methods

Following are the some of commonly used methods of generic sortedlist to perform add, search, insert, delete or sort operations in visual basic programming language.

 

MethodDescription
Add It is used to add an elements with specified key and value in SortedList<TKey, TValue>.
Clear It will remove all the elements from SortedList<TKey, TValue>.
ContainsKey It is used determine whether the specified key exists in the SortedList<TKey, TValue> or not.
ContainsValue It is used determine whether the specified value exists in SortedList<TKey, TValue> or not.
IndexOfKey It is used to get the index value of specified key stored in the SortedList<TKey, TValue>.
IndexOfValue It is used to get the index value of specified value stored in the SortedList<TKey, TValue>.
Remove It is used to remove an element from SortedList<TKey, TValue> with specified key.
RemoveAt It is used to remove an element at the specified index position from SortedList<TKey, TValue>.
TryGetValue It is used to get the value associated with the specified key.

Visual Basic Add Elements to SortedList

In visual basic, while adding elements to sortedlist we need to make sure that there will not be any duplicate keys because sortedlist will allow us to store a duplicate values but keys must be unique to identify the values in list.

 

Following is the example of adding a key/value pair elements to sorted list in different ways.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create a new sorted list with int keys and string values.

        Dim slst As SortedList(Of Integer, String) = New SortedList(Of Integer, String)()

        ' Add elements to the list. No duplicate keys allowed but values can be duplicate

        slst.Add(1, "Suresh")

        slst.Add(4, "Rohini")

        slst.Add(2, "Trishi")

        slst.Add(3, Nothing)

        ' Another way to add elements. If key not exist, then that key adds a new key/value pair

        slst(5) = "Trishi"

        ' Add method throws exception if key already in the list

        Try

            slst.Add(2, "Praveen")

        Catch __unusedArgumentException1__ As ArgumentException

            Console.WriteLine("An element with Key = '2' already exists.")

        End Try

        Console.WriteLine("*********List1 Elements********")

        ' Accessing elements as KeyValuePair objects

        For Each item As KeyValuePair(Of Integer, String) In slst

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        ' Creating and initializing list

        Dim slst2 As SortedList(Of String, Integer?) = New SortedList(Of String, Integer?) From {

                {"msg2", 1},

                {"msg3", 20},

                {"msg4", 100},

                {"msg1", Nothing}

            }

        Console.WriteLine("*********List2 Elements********")

        ' Accessing elements as KeyValuePair objects

        For Each item As KeyValuePair(Of String, Integer?) In slst2

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we are able to define a new generic sortedlist (slst, slst2) collections. Here, we added only the defined data type keys and values to the newly created lists (slst, slst2) in different ways.

 

As discussed, the Add method will throw an exception in case if we try to add a key (2) which is already existing so to handle that exception we used a try-catch block.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Add Elements to SortedList Example Result

 

If you observe the above result, by default all the list elements are sorted in ascending order based on the key and we got an exception when we tried to add a key (2) which is already existing and added a key (5) which is not existing in the list.

Visual Basic Access SortedList Elements

In visual basic, we have different ways to access sorted list elements i.e. either by using index positions or by iterating through the list using For / For Each loop.

 

Following is the example of accessing the sortedlist elements in different ways.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create new sorted list

        Dim slst As SortedList(Of Integer, String) = New SortedList(Of Integer, String)()

        slst.Add(1, "Suresh")

        slst.Add(4, "Rohini")

        slst.Add(2, "Trishi")

        slst.Add(3, "Praveen")

        ' Access value with key

        Dim val1 As String = slst(2)

        ' Access value with index position

        Dim val2 As String = slst.Values(2)

        ' Access key with index position

        Dim val3 As Integer = slst.Keys(2)

        Console.WriteLine("******Access Elements with Key, Index Position*****")

        Console.WriteLine("Value at Key '2': " & val1)

        Console.WriteLine("Value at Index '2': " & val2)

        Console.WriteLine("Key at Index '2': " & val3)

        Console.WriteLine("*********Access Elements with Foreach Loop********")

        For Each item As KeyValuePair(Of Integer, String) In slst

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.WriteLine("*********Access Elements with For Loop********")

        For i As Integer = 0 To slst.Count - 1

            Console.WriteLine("Key = {0}, Value = {1}", slst.Keys(i), slst.Values(0))

        Next

        Console.WriteLine("*********Sorted List Keys********")

        For Each item In slst.Keys

            Console.WriteLine("Key = {0}", item)

        Next

        Console.WriteLine("*********Sorted List Values********")

        For Each item In slst.Values

            Console.WriteLine("Value = {0}", item)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we are accessing generic list elements in different ways by using index positions, For and For Each loops based on our requirements.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Access Sorted List Elements Example Result

Visual Basic Remove Elements from SortedList

In visual basic, we have different methods to remove elements from the sorted list i.e. either by using Remove() or RemoveAt() methods.

 

Following is the example of deleting elements from the sorted list in visual basic programming language.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create new sorted list

        Dim slst As SortedList(Of Integer, String) = New SortedList(Of Integer, String)()

        slst.Add(1, "Suresh")

        slst.Add(4, "Rohini")

        slst.Add(2, "Trishi")

        slst.Add(3, "Praveen")

        slst.Add(5, "Sateesh")

        ' Remove element with key 2

        slst.Remove(2)

        ' Remove element at index position 2

        slst.RemoveAt(2)

        Console.WriteLine("*********Access Sorted List Elements********")

        Console.WriteLine()

        For Each item As KeyValuePair(Of Integer, String) In slst

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used Remove() method to delete particular key of element from the list and used RemoveAt() method to delete element at the specified index position.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Remove Elements from Sorted List Example Result

 

In case, if you want to remove all the elements from the sorted list, use Clear() method.

Visual Basic SortedList Check If Item Exists

By using ContainsKey() and ContainsValue() methods, we can check whether the specified element exists in the sorted list or not. In case, if it exists these methods will return True otherwise False.

 

Following is the example of using ContainsKey() and ContainsValue() methods to check for an item exists in sorted list or not in visual basic.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create new sorted list

        Dim slst As SortedList(Of Integer, String) = New SortedList(Of Integer, String)()

        slst.Add(1, "Suresh")

        slst.Add(4, "Rohini")

        slst.Add(2, "Trishi")

        slst.Add(3, "Praveen")

        slst.Add(5, "Sateesh")

        Console.WriteLine("Contains Key 2: {0}", slst.ContainsKey(2))

        Console.WriteLine("Contains Value 'Tutlane': {0}", slst.ContainsValue("Tutlane"))

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used ContainsKey() and ContainsValue() methods to check for particular keys and values exists in the sorted list (slst) or not.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Contains Key 2: True

Contains Value 'Tutlane': False

Visual Basic SortedList Overview

Following are the important points which we need to remember about the sorted list in visual basic.

 

  • SortedList is useful to store a collection of key/value pairs that are sorted by key based on the associated IComparer(Of T) implementation.
  • SortedList will allow us to store duplicate values but the keys must be unique to identify the values in the sorted list.
  • In SortedList, the keys cannot be null but the values can be null.
  • We can access SortedList elements either by using keys, index positions or with For and For Each loops. In For Each loop we need to use KeyValuePair(Of TKey, TValue) to get a key/value pairs from SortedList.