HashSet
This is an optimized set collection. With HashSet
we use the constructor to convert a String
array into a set. It can eliminate duplicates from a collection in a VB.NET program.
We can do similar things with HashSet
that we can do with Dictionary
. The main difference is that Dictionary
provides values, and HashSet
does not.
We declare a String
array of 6 Strings—3 of these strings are equal. Next, we create a HashSet
using the generics syntax in the VB.NET language.
HashSet
New function is an IEnumerable
(Of String
). This becomes the contents of the HashSet
.String
array implements the IEnumerable
interface
, which means it can be used by any method that handles IEnumerable
.String
array: all the duplicate Strings were removed.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 Modulecat dog cat leopard tiger cat cat dog leopard tiger
Join
The program uses the String.Join
Shared function. With String.Join
, you can convert an array into a String
. This makes the program require fewer lines.
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.