Visual Basic 2010 (Console) Guide
Sets (HashSets)

Set Basics

The HashSet data type allows you to store mathematical sets. These can be made up of any data type that you specify when you declare the HashSet variable.

  1. Union - The union of Set1 and Set2 would include each value from Set1 and each value from Set2 but no duplicates.
  2. Difference - The difference operation applied to Set1 and Set2 would result in a list of all the items in Set1 that do not appear in Set2.
  3. Intersection - The intersection of Set1 and Set2 results in a set which includes all of the values that exist in both sets.
  4. Membership - Checking to see if a value is in a set.

Example Program

' Declare two sets
Dim set1 As HashSet(Of String) = New HashSet(Of String)
Dim set2 As HashSet(Of String) = New HashSet(Of String)
' Set 1 Values
set1.Add("a")
set1.Add("f")
set1.Add("m")
set1.Add("r")
' Set 2 Values
set2.Add("d")
set2.Add("i")
set2.Add("m")
set2.Add("u")
' Output both sets
Console.WriteLine("Set 1: {0}", String.Join(",", set1.ToArray()))
Console.WriteLine("Set 2: {0}", String.Join(",", set2.ToArray()))
' Union of sets
Dim unionOfSets As HashSet(Of String) = New HashSet(Of String)(set1)
unionOfSets.UnionWith(set2)
Console.WriteLine("Union of Set 1 + Set 2 = {0}", String.Join(",", unionOfSets.ToArray()))
' Difference of sets
Dim differenceOfSets As HashSet(Of String) = New HashSet(Of String)(set1)
differenceOfSets.ExceptWith(set2)
Console.WriteLine("Difference of Set 1 - Set 2 = {0}", String.Join(",", differenceOfSets.ToArray()))
' Intersection of sets
Dim intersectionOfSets As HashSet(Of String) = New HashSet(Of String)(set1)
intersectionOfSets.IntersectWith(set2)
Console.WriteLine("Intersection of Set 1 * Set 2 = {0}", String.Join(",", intersectionOfSets.ToArray()))
' Membership
Console.WriteLine("Is the letter 'r' in Set 1? {0}", set1.Contains("r"))
Console.WriteLine("Is the letter 'r' in Set 2? {0}", set2.Contains("r"))
Console.ReadLine()

Having A Go (Sets)

  1. Set B is a subset of Set A if Set A is larger than Set B and all the items in Set B are in Set A. Use the MSDN to find out how to determine if one set is a subset of another.
  2. Write a program using the HashSet class to check if the following statements are true,
    1. A Intersect B = B Intersect A
    2. A Intersect (B Intersect C) = (A Intersect B) Intersect C
    3. A Union (B Union C) = (A Union B) Union C
    4. A Intersect (B Union C) = (A Intersect B) Union C
    5. A Intersect (A Union B) = A
    6. A Difference (B Union C) = (A Difference B) Intersect (A Difference C)
    7. A Difference (B Intersect C) = (A Difference B) Union (A Difference C)