Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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?

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

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();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!