This is your first visit inside The Matrix. Welcome!

The Matrix has you…

This place will take you into the mirage of learning C# programming language, without any previous coding experience being required

Follow the White Rabbit…█

Close
Tuesday, July 17, 2018 07:37

Hash Set

There are two types of Sets in the System.Collections.Generic namespace: SortedSet and HashSet. Both of them offer the functionality of storing non-duplicate items. The main difference between them is the fact that the SortedSet obviously has its items sorted. Therefor, if you do not care about the order in which the items are stored, you are better off performance-wise to use a HashSet. It will be slightly faster. In comparison with a List, a HashSet has a bit slower adding of elements. However, searching, reading or deleting elements is much, much faster, due to the hashing of the elements.

HashSet doesn’t have a capacity set. Its capacity increases along with the addition of elements.

We can directly assign the elements of an array to a HashSet, and the duplicate entries will be removed:

The HashSet object does not allow duplicate entry, hence the result will show the count of the data present in the HashSet less than the array count. The output will look like this:

The most important methods of the HashSet class are the following:

UnionWith() – we can use this method to union (join) the elements already contained in a HashSet with the elements of another collection.

The result would be:

Notice that the duplicate elements were removed from the merged HashSet.

ExceptWith() – This method is the complementary of UnionWith() – it will remove all the elements that are contained in both data structures, including the duplicate elements.

SymmetricExceptWith() – This modifies the final HashSet to include only the results that are present in one of the HashSet, but not both. All the matching elements will be removed.

The most important property of the HashSet is:

Count – returns an integer representing the total number of elements in the HashSet.

Comments

comments

Tags: ,

Leave a Reply