0

What I need to do is randomly shuffle an array of 25 numbers

int[] arr = Enumerable.Range(0, 24).ToArray();

So that it still has all the numbers from 0 to 24 but in a random order. What would be the simplest way to do it?

@edit;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        Random rnd = new Random();
        int[] arr = Enumerable.Range(0, 24).OrderBy(c => rnd.Next()).ToArray();

        public Form1()
        {
            InitializeComponent();
        }
    }
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Ayukawa
  • 11
  • 1
  • 3

1 Answers1

5

You can OrderBy(c => rnd.Next()) like this

Random rnd = new Random();
int[] arr = Enumerable.Range(0, 24).OrderBy(c => rnd.Next()).ToArray();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • Visual won't run this for me. It underlines 'random' and says 'a field initializer cannot reference the nonstatic field, method, or property' – Ayukawa Jun 14 '17 at 16:27
  • @Ayukawa See my updated answer. I renamed the variable's name to `rnd `. Fixed and no should work. Try it. – Salah Akbari Jun 14 '17 at 16:29
  • I actually noticed the mistake and changed 'rnd' to 'random' in both cases, so that is not the problem. – Ayukawa Jun 14 '17 at 16:31
  • I edited it, there's new code now – Ayukawa Jun 14 '17 at 16:39
  • @Ayukawa OK. You should cut that two lines and paste them to the under of `InitializeComponent` method. – Salah Akbari Jun 14 '17 at 16:40
  • That gives me aa different error, though. Now I can't refer to the 'arr' in a button I try to make. I get 'the name 'arr' does not exist in current context'. @S.Akbari – Ayukawa Jun 14 '17 at 16:42
  • @Ayukawa Change it like this: `Random rnd = new Random(); int[] arr; public Form1() { InitializeComponent(); arr = arr.OrderBy(c => rnd.Next()).ToArray(); }` – Salah Akbari Jun 14 '17 at 16:46
  • That worked. Thanks for help. – Ayukawa Jun 14 '17 at 17:01