c# – Create list without duplicate values

Question:

I have an int list and I want to save more numbers in it, but numbers that don't repeat.

How do I find if there is already a certain value in this list?

Answer:

What you're looking for is the structure called HashSet

If an element exists in the HashSet , it will not be added again. In other words, it is a "list" that does not accept duplicate values.

To find out if a value exists in the HashSet , you can call the HashSet.Contains() function:

var hashset = new HashSet<int>()
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
bool tem_4 = hashset.Contains(4);    // verdadeiro
bool tem_11 = hashset.Contains(11);  // falso
//verifica se o conjunto pertence ao hashset (caso não queira procurar um a um)
bool resultado = hashset.IsSupersetOf(new []{ 4, 6, 7 }); // verdadeiro

To add or remove it will call the functions:

hashset.Add(99);   // adiciona o valor 99 a "lista"
bool add99 = hashset.Add(99);   // tenta adicionar novamente 99 à "lista" (retorna falso)
//Continua havendo só um 99 na lista
hashset.Remove(99);   // remove o valor 99 da "lista"

And to iterate over the set you can use foreach

foreach(int valor in hashset)
{
    // faz algo
}

In addition, it is also possible to convert to list and Array :

int[] array = hashset.ToArray();
List<int> lst = hashset.ToList();
Scroll to Top