Hash Set Examples

Hash sets are one of the more unique collection types in the .NET framework. They work differently than a normal collection class such as a List. One of the main advantage of using a hashet is to avoid having duplicate elements in the collection. It’s internal use of standard Add, Remove, and Contains methods makes this one of the faster collection types to work with. Click more to see some examples I’ve provided.

HashSetSolution HashSetProgram

 
MyEqualityComparer.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySets
{
    public class MyEqualityComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            // Returning the values if the string in uppercase.
            return x.ToUpper() == y.ToUpper();
        }

        public int GetHashCode(string obj)
        {
            // Test variable to show what the hash code is.
            int getHashCode = obj.GetHashCode();

            // Forcing the object to be uppercase and returning the hash code.
            return obj.ToUpper().GetHashCode();
        }
    }
}

This is a simple equality comparer class that I’m using to show how you can use your own instead of what comes with .NET. This class is inheriting from the IEqualityComparer interface and is implementing the Equals and GetHashCode methods. I’ll be demonstrating the use of this class along with what the standard .NET equality comparer.

 
Program.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySets
{
    class Program
    {
        /// <summary>
        /// This program demonstrates how hash sets work and the unique element nature of hash sets.
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            executeDefaultHashSetExample();
            excecuteComparerHashSet();
            executeCustomComparer();

            Console.ReadLine();
        }

        // Private methods
        //
        // Method that executes various tasks for a hash set without any kind of comparer.
        private static void executeDefaultHashSetExample()
        {
            Console.WriteLine("----Executing The Hash Set Example Without Any String Comparer----");

            // Creating a list first for this demonstration.    
            List<string> listCities = new List<string>()
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London"
            };

            // Adding elements to the list after the initial creation.
            // Notice that I have a duplicate name going into the list. This can be done in a list
            // collection without any error unless you come up with a way to check.
            listCities.Add("Rome");
            listCities.Add("Los Angeles");

            // Displaying the contents of the list.
            Console.WriteLine("****List Contents Display****");
            foreach (var item in listCities)
                Console.WriteLine(item);
            Console.WriteLine();



            // Creating hash set with the same cities and add methods.
            HashSet<string> hashSetCities = new HashSet<string>
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London"
            };

            // Adding elements to the hash set. Since the Add method of hash set returns a boolean I'll check for that also.
            Console.WriteLine("****Items Actually Added To The Hash Set****");
            bool romeAdded = hashSetCities.Add("Rome");
            bool losAngelesAdded = hashSetCities.Add("Los Angeles");
            Console.WriteLine("Added Rome? {0}", romeAdded);
            Console.WriteLine("Added Los Angeles? {0}", losAngelesAdded);
            Console.WriteLine();

            // Displaying the contents of the hash set. 
            // Notice that the duplicate city name is only displayed once.
            Console.WriteLine("****Displaying The Contents Of The Hash Set");
            foreach (var item in hashSetCities)
                Console.WriteLine(item);
            Console.WriteLine();
        }

        // Method that executes tasks for a hash set using the .NET comparer.
        private static void excecuteComparerHashSet()
        {
            Console.WriteLine("----Executing The Hash Set Example Wit A .NET String Comparer----");

            // Creating hash set using the built in .NET String Comparer.
            HashSet<string> hashSetCities = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London"
            };

            // By using the .NET String Comparer you will see that inspection takes place before adding to the hash set.
            bool isThisAdded = hashSetCities.Add("LOS ANGELES");
            Console.WriteLine("LOS ANGELES ADDED? {0}", isThisAdded);

            hashSetCities.Add("San Diego");
            hashSetCities.Add("San Diego");

            foreach (var item in hashSetCities)
                Console.WriteLine(item);

            Console.WriteLine();
        }

        // Method that executes tasks for a hash set using a custom comparer.
        private static void executeCustomComparer()
        {
            Console.WriteLine("----Executing The Hash Set Example Wit A Custom String Comparer----");

            // Creating hash set using the built in .NET String Comparer.
            HashSet<string> hashSetCities = new HashSet<string>(new MyEqualityComparer())
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London"
            };

            // By using the .NET String Comparer you will see that inspection takes place before adding to the hash set.
            bool isThisAdded = hashSetCities.Add("LOS ANGELES");
            Console.WriteLine("LOS ANGELES ADDED? {0}", isThisAdded);

            hashSetCities.Add("San Diego");
            hashSetCities.Add("San Diego");

            foreach (var item in hashSetCities)
                Console.WriteLine(item);
        }
    }
}

If you’ve seem my other examples you know the drill moving forward. I’ve split this example up into 3 parts (methods). One method is executing a default hash set example, the second is using the built in .NET equality comparer,
and the third is using the custom equality comparer.

The first example is I’m creating a HashSet of string and adding some city names without any kind of string comparer. I didn’t bother creating a City class with properties, a constructor, methods, etc… However you can see that this can be done and same rules will apply if it was a collection of objects. You can see that I’m creating a bool variable and defining it using the Add method. This is because the HashSets add method will check the hash of what I’m wanting to add, see if it already exists, and adding it if it doesn’t. One must be careful here though. Without any kind of string comparer you can run into issues. Say if you decide to make all the characters in all caps.

The second example is using the built in string comparer class built into the .NET framework. And the I’m demonstrating by adding the city of Los Angeles in all caps. By using this string comparer class is will ignore the case and tell me that that city has already been added. I’m further proving this by adding the city of San Diego twice. However when you run the program you will see that it’s only been added once. This is because the internal string comparer class sees that it’s already been added. Since there isn’t any kind of exception thrown you will have to do something like I’ve done with the bool variables to check.

The third example is using a custom string comparer class. I’m not doing much with the implemented Equals and GetHashCode methods other than what the default string comparer does. This is just to show that you can create your own if the default one isn’t good enough. Again you can see that I’m trying to add San Diego twice but it doesn’t show when the program is run.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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