You can use combination of foreach
loop and return value of HashSet<int>.Add
method.
With this approach you don't need to loop all values if duplication have been found early. Where GroupBy
should always loop all values.
public static bool HaveDuplicates(this IEnumerable<int> values)
{
var set = new HashSet<int>();
foreach (var value in values)
{
if (set.Add(value) == false)
{
return true;
}
}
return false;
}
Use it as extension method
var values = new List<int>() { 1, 5, 6, 1, 2, 5, 6, 7, 8, 9 };
if (values.HaveDuplicates())
{
// have duplicates
}
I'm trying to use it in a do while loop. Inside the do, I generate a
random number from 1 to 9, and add it to the Values list. if the
number that gets generated is one already in the list, then run the
loop over again. If not, escape the loop
Use HashSet<T>
for saving generated number. HashSet<T>
will check for duplication with O(1) operations, where
var values = new HashSet<int>();
do
{
var generatedValue = GenerateNumber(); // your generation logic
if(values.Add(generatedValue) == false)
{
break;
}
}
while(yourCondition);
You can loop HashSet as other collections or convert it to List
if you need
var numbers = values.ToList();