I have a list of int
and I want to save more numbers in it, but numbers that do not repeat themselves.
How do I find if it already has a certain value in this list?
I have a list of int
and I want to save more numbers in it, but numbers that do not repeat themselves.
How do I find if it already has a certain value in this list?
What you are looking for is the structure called HashSet
If an element exists in HashSet
, it will not be added again.
In other words, it is a "list" that does not accept duplicate values.
To know if a value exists in HashSet , you 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 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();
You have three options: Set
, HashSet
and SortedSet
. Each one with its characteristic and depends on its need one is better than the other.
.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 the ordered order that you determine (in the order they are entered in the "list".
Do not confuse being ordered with being sorted ( sorted ) in a particular order. If you need sorting (increasing numeric, for example) there you would need a SortedSet ).
What if there is no Set
in .NET?
Implementing your own framework is not difficult.
But this takes time, if you do not master the subject you will probably make an inefficient implementation with bugs .
Use a third-party implementation that is well-recommended and tested.
I'm talking about the PowerCollections library. See the Set structure source . Of course there are other options but this one is good.
In spite of its utility, generally a% w (O (N)) is much slower than a% w (O (1), although there are cases where this is not true). That is why .Net does not implement it. The Set
(O (logN)) (known as HashSet
in some implementations) is usually faster and may even be better than SortedSet
in some situations. Understand the Big O notation .