Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

hashset

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?

like image 268
mathenthusiast8203 Avatar asked Jun 25 '15 14:06

mathenthusiast8203


2 Answers

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?

like image 190
Habib Avatar answered Sep 28 '22 01:09

Habib


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

like image 42
nozzleman Avatar answered Sep 28 '22 00:09

nozzleman