Create list without duplicate values

Asked

Viewed 3,795 times

14

I have a list of int and I want to save more numbers in it, but numbers that don’t repeat.

How do I find out if you already have a certain value on this list?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

2 answers

14

What you’re looking for is the structure called HashSet

If an element exists in HashSet, it will not be added again. I mean it’s a "list" that does not accept duplicate values.

To know if a value exists in Hashset, can call the function HashSet.Contains():

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 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 the 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();

5

You have three options: the Set, the HashSet and the SortedSet. Each with its own characteristic and depends on its need one is better than the other.

The . NET does not have an implementation of the structure Set that can be the most suitable for what you want. The Set stores the data in order (ordered) which you determine (in the order they are inserted in the "list".

Don’t confuse being ordained with being classified (Sorted) in a certain order. If you need the classification (increasing numeric, for example) there you would need a Sortedset).

What to do if there isn’t one Set no . NET?

  • Implement your own structure, it is not difficult.

    But this takes time, if not master the subject will probably make an implementation inefficient and with bugs.

  • Use a third-party implementation that is well recommended and tested.

    I’m talking about the library Powercollections. See the source of the Set structure. Of course there are other options but this is good.

Characteristics and performance

Despite its usefulness, generally a Set ((n)) is much slower than a HashSet ((1), although there are cases where this is not true). Therefore . NET does not implement it. The SortedSet (O(log n)) (known as TreeSet in some implementations) is usually faster and may even be better than the HashSet in some situations. Understand the Big O notation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.