HomeSearch

VB.NET HashSet Example

Use HashSet to store unique elements. HashSet is an optimized set collection.

HashSet is an optimized set collection. We use it to eliminate duplicates from a collection in a VB.NET program. With HashSet we use the constructor to convert a String array into a set. This also eliminates all duplicates.

Example. We declare a String array of six Strings. Three of these strings are equal. Next, we create a HashSet using the generics syntax in the VB.NET language. The sole argument to the HashSet New function is an IEnumerable(Of String).

Note: Recall that the String array implements the IEnumerable interface, which means it can be used by any method that handles IEnumerable.

Finally: We convert back into a String array: all the duplicate Strings were removed.

VB.NET program that uses HashSet Module Module1 Sub Main() ' String array. Dim a As String() = {"cat", "dog", "cat", "leopard", "tiger", "cat"} Console.WriteLine(String.Join(" ", a)) ' Create HashSet. Dim hash As HashSet(Of String) = New HashSet(Of String)(a) ' String array. a = hash.ToArray() Console.WriteLine(String.Join(" ", a)) End Sub End Module Output cat dog cat leopard tiger cat cat dog leopard tiger

Join. One interesting thing about this program is the use of the String.Join Shared function. With String.Join, you can convert an array into a String. This makes the above program require fewer lines.Join

Summary. With the HashSet collection type, you can collapse duplicate elements of an array. We showed String arrays here. But this approach works with other types as well. HashSet implements ISet, which means it also has many helpful Functions.

Note: SortedSet is also available. It uses a different implementation for looking up keys. Usually a hashed algorithm is faster.

Dictionary
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.