Question

I'm not sure, if this question is unique, but I couldn't find the answer.

I want a good way to get numbers between 1 to 9 (including 9) randomly in C#, and I want to have all the 9 numbers. So I need a function that returns 9 numbers between 1 to 9 and I need every number exactly once.

for example, the result would look like this: 4,3,2,6,9,7,1,5,8

Was it helpful?

Solution

I would just do this:

var rnd = new Random();

var numbers =
    Enumerable
        .Range(1, 9)
        .OrderBy(x => rnd.Next())
        .ToArray();

An example result I got was:

example result

OTHER TIPS

Here You Go:

public void Shuffle(List<int> list)
{
    Random random = new Random();
    for (int i = 0; i < list.Count; i++)
    {
        int k = random.Next(i + 1);
        int val = list[k];
        list[k] = list[i];
        list[i] = val;
    }
}

Usage:

List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Shuffle(list);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top