What is the difference between HashSet and List?

Unlike a List<> …

  1. A HashSet is a List with no duplicate members.

  2. Because a HashSet is constrained to contain only unique entries, the internal structure is optimised for searching (compared with a list) – it is considerably faster

  3. Adding to a HashSet returns a boolean – false if addition fails due to already existing in Set

  4. Can perform mathematical set operations against a Set: Union/Intersection/IsSubsetOf etc.

  5. HashSet doesn’t implement IList only ICollection

  6. 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!

Leave a Comment