EN
C# / .NET - random sort array
0 points
In this article, we would like to show you how to sort array in random order working with C#.
Quick solution:
xxxxxxxxxx
1
int[] myArray = { 1, 2, 3, 4, 5 };
2
3
Random random = new Random();
4
5
myArray = myArray.OrderBy(x => random.Next()).ToArray();
In below example, we present how to use OrderBy()
method combined with Random.Next()
to sort array in random order.
xxxxxxxxxx
1
int[] myArray = { 1, 2, 3, 4, 5 };
2
3
Random random = new Random();
4
5
myArray = myArray.OrderBy(x => random.Next()).ToArray();
6
7
foreach (int i in myArray)
8
{
9
Console.WriteLine(i);
10
}
Example output:
xxxxxxxxxx
1
1
2
4
3
5
4
3
5
2