As commented,
Manieiro :
Set "how many numbers repeated", this can be interpreted as
various forms.
The proposed answer presents a solution that depends exactly on which question is being asked.
Gabriel Coletta
int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
var meuHashSet = new HashSet<int>(array1);
var valoresRepetidos = array1.Length - meuHashSet.Count;
The result is 5 , a result of the original size difference of Array
subtracted from its Distinct
, which can also be written as Linq
int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
var quantidadeRepetidos = array1.Length - array1.Distinct().Count();
However, we come to a subjective point, 5 actually represents the number of repetitions of the values after their first occurrences, in other words, 5 is equal amount of duplicates or recurrences.
But when we look at the original set [2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8]
, we can see that it has 8 elements of repeated values (which have more than one occurrence). What can be seen more easily by rearranging and removing unique occurrences
[2,2,2,5,5,8,8,8]
. And this difference greatly impacts the purpose of the query and what you intend to do with that result.
But the number of repeated numbers can also be aimed at knowing the number of numbers that have had more than one occurrence in the [2,5,8]
case.
Below I leave a sample script only to demonstrate how I could respond to variations in interpretation according to the specified goal, using some lists to facilitate manipulation and a single for()
.
int[] arrayOrignal = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
var listUnicos = new List<int>();
var listRepetem = new List<int>();
var listDuplicatas = new List<int>();
int tamanho = arrayOrignal.Length;
for (int i = 0; i < tamanho; i++)
{
var elemento = arrayOrignal[i];
if (arrayOrignal.Where(x => x.Equals(elemento)).Count().Equals(1))
listUnicos.Add(elemento);
else if (!listRepetem.Contains(elemento))
listRepetem.Add(elemento);
else
listDuplicatas.Add(elemento);
}
//[2, 5, 8, 10, 23, 4] -> 6 valores distintos
int[] arrayDistinto = arrayOrignal.Distinct().ToArray();
//[10, 23, 4] -> 3 valoes únicos
int[] arrayUnicos = listUnicos.ToArray();
//[2, 5, 8] -> 3 valores que repetem
int[] arrayRepetem = listRepetem.ToArray();
//[2, 2, 5, 8, 8] -> 5 valores recorrentes
int[] arrayDuplicatas = listDuplicatas.ToArray();
//[2, 5, 8, 2, 2, 5, 8, 8] -> 8 valores repetidos
int[] arrayRepetidos = arrayOrignal.Where(x => listDuplicatas.Contains(x)).ToArray();