VB.NET HashSet Example

Set collection

You want to eliminate duplicates from a collection using the HashSet type in your VB.NET program. With HashSet, you can use the constructor to convert a String array into a set. This also eliminates all duplicates.

Example

Note

To begin, we declare a String array of six Strings; three of the 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); recall that the String() array implements the IEnumerable interface. Finally, we convert back into a String() array: all the duplicate Strings were removed.

This VB example uses HashSet, which is an optimized set collection.

Program that uses HashSet [VB.NET]

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 String Function

Summary

The VB.NET programming language

With the HashSet collection type, you can collapse duplicate elements of an array. Although we showed String arrays here, this approach works with other types as well. HashSet implements ISet, which means it also has many Functions for manipulating its own data and that of other sets.

VB.NET Tutorials
.NET