HashSet – Part 2


To go a little bit in deep HashSet is a collection class with the semantics of a set. There are no duplicates no matter how many times you add an item to the set as I mentioned in the example. It is unordered. It supports common Set operations like intersection, union, and subset operations. All of us who have done Set Theory long long back would love this.

Before jumping into the details of how HashSet works for those who need a little bit brushing of Set terminologies (like me) here are some good resources –
SubSet (Wikipedia) – http://en.wikipedia.org/wiki/Subset
SuperSet (Wikipedia) – http://en.wikipedia.org/wiki/Superset


Here’re some examples of the Set functionality provided by HashSet –

Subset and Superset checking:
HashSet<int> superSetNos = new HashSet<int> { 1, 2, 3, 4, 5, 6 };
HashSet<int> subSetNos = new HashSet<int> { 1, 2, 3};

bool isSuperset = superSetNos.IsSupersetOf(subSetNos);
bool isProperSuperset = superSetNos.IsSupersetOf(superSetNos);
// Any set is a superset of itself, but not a proper superset. So isProperSuperSet would be False

Console.WriteLine(isSuperset); // Output would be True
Console.WriteLine(isProperSuperset); // Output would be False

       bool isSubset = subSetNos.IsSubsetOf(superSetNos);
       // Any set is a subset of itself, but not a proper subset. So isProperSubSet would be False
       bool isProperSubset = subSetNos.IsProperSubsetOf(subSetNos); 

       Console.WriteLine(isSubset); // Output would be True
       Console.WriteLine(isProperSubset); // Output would be False

      
Console.ReadLine();

                Intersection:
               
HashSet<int> firstSet = new HashSet<int> { 1, 3, 5, 7, 9 };
       
HashSet<int> secondSet = new HashSet<int> { 7, 9, 11, 13, 17 };

       firstSet.IntersectWith(secondSet);
      
// firstSet would now have 7, 9 which is common among both original firstSet and secondSet

                 Union:
                
HashSet<int> firstSet = new HashSet<int> { 1, 3, 5, 7, 9 };
       
HashSet<int> secondSet = new HashSet<int> { 7, 9, 11, 13, 17 };

       firstSet.UnionWith(secondSet);
       
// firstSet would now have 1, 3, 5, 7, 9, 11, 13, 17 which is common among both original firstSet and secondSet

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s