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?
Asked
Active
Viewed 8.4k times
54
-
1This is a List, not an array, though. – mathenthusiast8203 Jun 25 '15 at 14:18
-
1For this kind of question they are both `IList
`. – Richard Jun 25 '15 at 14:19 -
The answer addresses the problem—"HashSet has a constructor that takes an IEnumerable". – David Sherret Jun 25 '15 at 14:20
3 Answers
98
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?
10
An alternative way would be
var yourlist = new List<SomeClass>();
// [...]
var uniqueObjs = yourlist.Distinct(); //Gives you a List with unique Objects of the List.
Note that this is only possible, if SomeClass
overrides GetHashCode
and Equals
in some way. This is also true for
var uniqueObjs = new HashSet<SomeType>(yourOriginalList);
Otherwise you could implement you own IEqualityComnparer
-class and pass it to distinct.
Note that with the Distinct()
approach, you can also look for distinct property values of the object in the list:
var uniqueNames = yourlist.Select(obj => obj.Name).Distinct();
and some more...

nozzleman
- 9,529
- 4
- 37
- 58
-
I much prefer this answer to the ones that answer the specific question. "I want a house with 2 doors, so I'm going to bulldoze this house with 1 door and build a new house from scratch" – Phylogenesis Jun 25 '15 at 14:22
-
1you would need to implement IEquatable on 'SomeClass' for that to work – yohannist Jun 25 '15 at 14:22
-
@YTAM as far as i am concerned, this is also the case if you want to create a new Hashset based on the original list. – nozzleman Jun 25 '15 at 14:26
-
And the mere fact that they're considered duplicate means they must be mathematically/logically equatable in some way. – Phylogenesis Jun 25 '15 at 14:30
7
If your type implements IEquatable<T>
, Equals()
and GetHashCode()
correctly, then you don't need to do the de-duplication yourself. You can use Linq's Distinct()
to do so like this:
myList = myList.Distinct().ToList();

Matthew Watson
- 104,400
- 10
- 158
- 276
-
Most of the time I need a set to remove duplicates from a list. This is a great way to achieve that. – Jabba Aug 06 '20 at 11:10