C# – How to shuffle an array?
The easiest way to shuffle an array in C# is using Random.Shuffle
. This method has been introduced in .NET 8 and works both with arrays and spans.
The suffling is done in-place (the existing array/span is modified, as opposed to creating a new one and leaving the source unchanged).
In terms of signatures, we’ve got:
public void Shuffle<T> (Span<T> values);
public void Shuffle<T> (T[] values);
Code language: C# (cs)
And for a simple usage example:
int[] foo = [1, 2, 3];
Random.Shared.Shuffle(trainingData); // [2, 1, 3]
Code language: C# (cs)
One Comment