Quote for the Week

"Learn to enjoy every moment of your life"

Tuesday, December 16, 2014

HashSet in C#.net

A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object.

For more information on hashing, check out the HashMap category.

Things to remember:
– A HashSet is not synchronized, so not thread-safe.
– Its elements are not ordered
– Add an element to the HashSet with the method add(Object o)
– Remove an element with the method remove(Object o)
– Remove all elements with the method clear()
– Get the number of elements with the method size()


Note:

This internally calls the UnionWith method to eliminate the duplications. ToArray transforms the HashSet into a new array.

Creation of Hashset<>

The following line of code describes how to create the hashset in C#:

HashSet<int> firstset = new HashSet<int>();
HashSet<int> secondset = new HashSet<int>();



Add elements in the Hashset<>

To add an element to the Hashset we use the add() method like:

for (int i = 1; i < 10; i++)
{
   firstset.Add(5 * i);
}
for (int j = 1; j < 10; j++)
{
   secondset.Add(10 * j);
}

Prints the elements of hashset using foreach loop

Write the following code to print the elements of the hashset:

namespace ConsoleApplication14
{
    class Program
    {
        static void Main(string[] args)
        {
            HashSet<int> firstset = new HashSet<int>();
            HashSet<int> secondset = new HashSet<int>();
            for (int i = 1; i <= 10; i++)
            {
                firstset.Add(5 * i);
            }
            for (int j = 1; j <=10; j++)
            {
                secondset.Add(10 * j);
            }
            Console.WriteLine("The table of five(5) is:");
            foreach (int a in firstset)
            {
                Console.WriteLine(a);
            }
            Console.WriteLine("The table of Ten(10) is:");
            foreach (int b in secondset)
            {
                Console.WriteLine(b);
            }
        }
    }
}

No comments: