Q: Randomize a List in C#

D: What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.

Test Case #3


File ID: #1262619-1-cc


  public static List Shuffle(List listToShuffle)
{
Random rng = new Random ();
int n = listToShuffle.Count;
while (n > 1) {
n--;
int k = rng.Next (n + 1);
T value = listToShuffle [k];
listToShuffle [k] = listToShuffle [n];
listToShuffle [n] = value;
}
return listToShuffle;
}

  1. I would like to point out, that the comparison is flawed. Using new Random() in a loop is the problem, not the randomness of Random [Explanation](http://stackoverflow.com/questions/3053807/random-number-in-a-loop/3053811#3053811)
  2. It is a good idea to pass an instance of Random to the Shuffle method rather than create it inside as if you are calling Shuffle lots of times in quick succession (e.g. shuffling lots of short lists), the lists will all be shuffled in the same way (e.g. first item always gets moved to position 3).
  3. What if list.Count is > Byte.MaxValue? If n = 1000, then 255 / 1000 = 0, so the do loop will be an infinite loop since box[0] < 0 is always false.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: