HashSet that preserves ordering

Standard .NET HashSet do not preserve the insertion order. For simple tests the insertion order may be preserved due to an accident, but it’s not guaranteed and would not always work that way. To prove that it is enough to do some removals in between. See this question for more information on that: Does HashSet … Read more

Define: What is a HashSet?

A HashSet holds a set of objects, but in a way that 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. Take a … Read more

How does HashSet compare elements for equality?

It uses an IEqualityComparer<T> (EqualityComparer<T>.Default unless you specify a different one on construction). When you add an element to the set, it will find the hash code using IEqualityComparer<T>.GetHashCode, and store both the hash code and the element (after checking whether the element is already in the set, of course). To look an element up, … Read more