This will use a method that will work:
public List<int> Randomize(int[] numbers) { List<int> randomized = new List<int>(); List<int> original = new List<int>(numbers); Random r = new Random(); while (original.Count > 0) { int index = r.Next(original.Count); randomized.Add(original[index]); original.RemoveAt(index); } return randomized; }
Edit:
Another way could be to use LINQ extension methods for IEnumerable<T>
collections:
var random = new Random(); List<int> randomized = numbers.OrderBy(x => random.Next()).ToList();
If you want to have an array instead of List<int>
, you can use .ToArray()
instead.
Of course, this will work for any int
array, and not just for 1, 2, 3, ..., n
. You can even make a general method in T
source share