Alan2
Alan2

Reputation: 24602

How can I pick one row from an array at random?

When my application starts up I do this:

Random rand = new Random();

I then have this code that create a list of phrases. What I would like to do is to select the PhraseId of just one of the rows in that list. I am trying with rand but getting very confused about how to do this. Here is what I have so far:

var phrases = App.selectedPhrases.All.Where(x => x.Points > 1).ToList();
if (phrases.Count == 0) return;
var indx = (int)rand.Next(phrases.Count) + 1;
var id = phrases[indx].PhraseId;

Can someone confirm for me, is this the correct way to do it and will it work no matter how many rows are in the list and if there is just one element will it pick that or should I code differently for that case?

Upvotes: 1

Views: 57

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

just change

var indx = (int)rand.Next(phrases.Count) + 1;

to:

var indx = rand.Next(phrases.Count);

0 <= rand.Next(phrases.Count) < phrases.Count

as index stars from 0 but + 1 in rand.Next(phrases.Count) + 1 would exclude 0 index and would include indx == phrases.Count which is out of range.

Upvotes: 4

Related Questions