How can I check if there are two or more equal values in one array?
eg. in this example, i want the program to tell me that there is a pair of 2 and a pair of 4
int[] array1 = { 1, 2, 4, 2, 4 };
Using Linq
var result = array1.GroupBy(i=>i)
.Select(g=>new {Value = g.Key, Count = g.Count()})
.Where(x=>x.Count>1)
.ToList();
foreach (var pair in result)
{
Console.WriteLine("PAIR: " + pair.Value + " COUNT: " + pair.Count);
}
[EDIT] Sorry, this answers the question "How can I check if there are two or more equal values in one array?", but it doesn't tell you the actual duplicates...
This would work, but possibly it isn't the most efficient way!
int[] array1 = { 1, 2, 4, 2, 4 };
if (array1.Distinct().Count() < array1.Length)
Console.WriteLine("Contains Dupes");
If you want the most efficient approach:
bool containsDupes(int[] array)
{
for (int i = 0; i < array.Length - 1; ++i)
{
int n = array[i];
for (int j = i+1; j < array.Length; ++j)
if (array[j] == n)
return true;
}
return false;
}
I don't think you can get much more efficient than that. It will return as soon as it finds any match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With