0

I have a c# int array that contains numbers from 1 to 100 that means that

myArray[0] = 1;
myArray[1] = 2;
....
myArray[99] = 100;

But I want to rearrange them in this array randomly, is it possible in c# ?

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
Firas Yahyaoui
  • 61
  • 1
  • 2
  • 6

1 Answers1

3

Using Random and Linq, you can do it easily:

Random r = new Random();

myArray = myArray.OrderBy(x => r.Next()).ToArray();

The above provides a random sort order for each element in the array using a Random object.

You need to add using System.Linq; at the top of your file in order to use OrderBy extension method.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • @HenkHolterman How would that generate duplicates ? If the original array has unique numbers. – Zein Makki Jul 09 '16 at 16:21
  • _"provides a random sort order"_ - well, random, but not as random as can be. – CodeCaster Jul 09 '16 at 16:22
  • @فراساليحياوي it is one element inside the array. OrderBy is a loop internally. x is one element in the array in one iteration. as if you said `foreach(var x in myArray)` – Zein Makki Jul 09 '16 at 17:20