Select a random object from an array or other collection in C#

The Random class provides methods for generating random numbers. The following code uses a Random object to pick a string from an array of lines taken from a TextBox.

// Pick a random name.
private void btnPick_Click(object sender, EventArgs e)
{
// Get the text lines.
string[] lines = txtPeople.Lines;

// Make a Random object.
Random rand = new Random();

// Get a random index between
// 0 inclusive and lines.Length exclusive.
int index = rand.Next(0, lines.Length);

// Display the result.
txtResult.Text = lines[index];
}

The code gets the lines into an array. It then creates a new Random object. The empty constructor automatically initializes the object "randomly" so you don't get the same sequence of random numbers each time you run the program.

The code then simply uses the object's Next method to get a random number between 0 inclusive and lines.Length exclusive. In other words, the returned number could be as small as 0 or as big as lines.Length - 1.

The same technique works for lists or other collections.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.