Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse the HashSet class to represent sets and perform set operations in Visual Basic .NET
DescriptionThis example shows how to use the HashSet class to represent sets and perform set operations in Visual Basic .NET.
Keywordsalgorithms, sets, set operations, overloaded operators, HashSet, union, intersection, XOR, Visual Basic .NET, VB.NET
CategoriesAlgorithms, Software Engineering
 

The HashSet class can represent objects in a set and perform set operations such as finding the union or intersection of two sets.

When the program starts, the following code builds two sets and performs some operations with them.

 
' Make some sets and perform operations on them.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    Dim owns_a_car As New HashSet(Of String)()
    Dim owns_a_bike As New HashSet(Of String)()

    owns_a_bike.Add("Alice")
    owns_a_bike.Add("Bob")
    owns_a_bike.Add("Fred")
    owns_a_bike.Add("Dan")

    owns_a_car.Add("Cindy")
    owns_a_car.Add("Dan")
    owns_a_car.Add("Emma")
    owns_a_car.Add("Bob")
    owns_a_car.Add("Fred")

    txtOwnsABike.Text = String.Join(", ", _
        owns_a_bike.ToArray())
    txtOwnsACar.Text = String.Join(", ", _
        owns_a_car.ToArray())

    ' Intersection.
    Dim owns_both As New HashSet(Of String)(owns_a_car)
    owns_both.IntersectWith(owns_a_bike)
    txtOwnsBoth.Text = String.Join(", ", _
        owns_both.ToArray())

    ' Union.
    Dim owns_either As New HashSet(Of String)(owns_a_car)
    owns_either.UnionWith(owns_a_bike)
    txtOwnsEither.Text = String.Join(", ", _
        owns_either.ToArray())

    ' Xor.
    Dim owns_one As New HashSet(Of String)(owns_a_car)
    owns_one.SymmetricExceptWith(owns_a_bike)
    txtOwnsOne.Text = String.Join(", ", owns_one.ToArray())
End Sub
 
The code makes two sets named owns_a_car and owns_a_bike, and displays them.

The program makes a copy of owns_a_car, uses its IntersectWith method to find the intersection of the two sets, and displays the result (people who own both cars and bikes).

The program makes another copy of owns_a_car, uses its UnionWith method to find the intersection of the two sets, and displays the result (people who own either cars or bikes or both).

Finally the program makes a third copy of owns_a_car, uses its SymmetricExceptWith method to find items in one set or the other but not both (Xor), and displays the result (people who a bike or car but not both).

The HashSet class provides other set-related methods such as IsSubsetOf, IsPropertySubsetOf, IsSupersetOf, etc.

 
 
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated