user3796130
user3796130

Reputation:

How to Randomize all the entire content inside of array C#

i have my Array {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15} and i want to randomize 10 numbers between 15,each one!

so,when if i click a button will be something like this

{2,4,5,6,8,9,12,13,14,15} and i want to list all the 10 numbers that was chosen

I found this

string[] names = new string[] {
            "Aaron Moline1", 
            "Aaron Moline2", 
            "Aaron Moline3" 
        };
        Random rnd = new Random();
        string[] MyRandomArray = names.OrderBy(x => rnd.Next()).ToArray();

its almost what I want, but I can't choose the limit of numbers I want. So, the output will be something like this:

{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15} //15 numbers instead of 10

So, to be clear, I want to select 10 numers randomly but they should be in oirder.

Upvotes: 1

Views: 92

Answers (1)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

Shuffle array. Take first 10 items. order again:

int[] names = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
Random rnd = new Random();
int[] MyRandomArray = names.OrderBy(x => rnd.Next()).Take(10).OrderBy(x => x).ToArray();

foreach (var s in MyRandomArray)
{
    Console.WriteLine(s);
}

Upvotes: 3

Related Questions