Search code examples
.netlisthashsetdifference

What is the difference between HashSet<T> and List<T>?


Can you explain what is the difference between HashSet<T> and List<T> in .NET?

Maybe you can explain with an example in what cases HashSet<T> should be preferred against List<T> ?


Solution

  • 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!