Unlike a List<>
- A HashSet is a List with no duplicate members.
- Because a HashSet is constrained to contain only unique entries, the internal structure is optimized for searching (compared with a list) – it is considerably faster
- Adding to a HashSet returns a boolean – false if addition fails due to already existing in Set
- Can perform mathematical set operations against a Set: Union/Intersection/IsSubsetOf etc.
- HashSet doesn’t implement IList only ICollection
- You cannot use indices with a HashSet, only enumerators.
The main reason to use a HashSet would be if you are interested in performing Set operations.
Given 2 sets: hashSet1 and hashSet2
//returns a list of distinct items in both sets HashSet set3 = set1.Union(set2);
flies in comparison with an equivalent operation using LINQ. It’s also neater to write!
Thanks to BonyT for this answer.