C # HashSet Advantages

Finally added a Set data structure to C# in the .NET Framework 3.5. It is a powerful data structure that makes programmers' lives easier…

C#Set is called HashSet. It is modeled on a mathematical set, meaning that the elements must be unique. In other words, Set guarantees that there are no duplicate elements.

Now why create a Set data structure in C#, just check a list before adding elements to see if it already exists? The answer is: this is because searching for a normal list is slow. HashSet is fundamentally designed to allow quick searches and make inserts faster.

Collections have different implementations. Some make the insertion and lookup operations super fast by hashing elements. However, this means that the order in which the elements are added will be lost. Other implementations preserve the order of addition at the expense of slower runtimes.

The HashSet class in C# is used in the second method, so the order of the elements is preserved. It is still much faster than the regular list. Some basic benchmark tests show that HashSets are much faster when dealing with major types (int, double, bool, etc.). Work class objects are much faster. So the key is the HashSet is fast.

The only problem with HashSet is that the standard is inaccessible. To access an element, you can use an enumerator or use a built-in function to convert a HashSet to a List and iterate over it.

Source by Armando Pensado