Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

383
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda