1

I'm new to C# and have the following piece of code:

int[] ids = { 190483, 184943, 192366, 202556, 169051, 177388, 170890, 146562, 189509 };

for (var i=0; i<50; i++)
{
    int randomID = *randomNumberFromIDList*;
    Console.WriteLine("Random ID:" + randomID);
}

As you can see, all I'm looking to do is with each loop assign and display a random ID from the list with the randomID being set as an int.

Is there a simple way to do this?

1
  • You'll need an instance of Random class, say it's named random. Then just call random.Next(ids.Count) and use it as an index. Commented Nov 13, 2015 at 11:23

3 Answers 3

3

Create a Random instance and call the Next(int, int) function to get number between inclusive lowest number and exclusive highest number:

int[] ids = { 190483, 184943, 192366, 202556, 169051, 177388, 170890, 146562, 189509 };

var random = new Random();
for (var i=0; i<50; i++)
{
    int randomID = ids[random.Next(0, ids.Length)];
    Console.WriteLine("Random ID:" + randomID);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@GiorgiNakeuri As stated the second argument is the exclusive upper bound. Therefor Next(0, 1) will always generate 0. See msdn
1

You can use Random class for this and generate random number between 0 and length of an array:

var r = new Random();   
for (var i=0; i<50; i++)
    Console.WriteLine("Random ID:" + ids[r.Next(0, ids.Length)]);

Comments

0

You could use a random to generate a index starting from 0 to the size of your array, with this index you acess a position of your array and get a random ID.

int[] ids = { 190483, 184943, 192366, 202556, 169051, 177388, 170890, 146562, 189509 };

var random = new Random();

for (var i = 0; i < 50; i++)
{
     int arrayPos = random.Next(0, ids.Count() - 1);
     int randomID = ids[arrayPos];
     Console.WriteLine("Random ID:" + randomID);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.