How to convert List<T> to HashSet<T> in C#?

mathenthusiast8203 picture mathenthusiast8203 · Jun 25, 2015 · Viewed 52.1k times · Source

I have a List that has duplicates of objects. To solve that, I need to convert the List into a HashSet (in C#). Does anyone know how?

Answer

Habib picture Habib · Jun 25, 2015

Make sure your object's class overrides Equals and GetHashCode and then you can pass the List<T> to HashSet<T> constructor.

var hashSet = new HashSet<YourType>(yourList);

You may see: What is the best algorithm for an overridden System.Object.GetHashCode?