Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

379
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda