HashSet Example
This page was last reviewed on Sep 25, 2022.
Dot Net Perls
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.
Type notes. 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.
Example. 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.
And The argument to the HashSet New function is an IEnumerable(Of String). This becomes the contents of the HashSet.
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.
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
cat 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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2022 (edit).
© 2007-2024 Sam Allen.