In my opinion, you should change your approach.
Instead of thinking "I'll generate random indexes to pick my numbers", where you have to be sure you don't get any duplicates, I would simply shuffle the array and take the X first you need. That way, you don't need to worry about indexes or duplicates.
So your second for loop would be changed to
drawHolder = numberHolder.OrderBy(x => new Guid()).Take(numAmount);
(Please note I've used new Guid()
so you can remove your RandomNumber
declaration line. As discussed before, a GUID is a unique value and not meant for to be used as a random gen. You could also use x => RandomNumber.Next()
, but if you really need a strong and reliable shuffe, read about Fisher-Yates)
You can also replace your numberHolder array with a simple Enumerable.Range
So your whole code would become (And please note I've changed your method name to use C# conventions, method names should be in PascalCase)
public string DrawNumbers(int numLimit, int numAmount)
{
drawHolder = Enumerable.Range(0, numLimit).OrderBy(x => new Guid()).Take(numAmount);
return string.Join(", ", drawHolder);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…