How to select a random string from an array of strings?
This article demonstrates how to pick a random string from an array of strings.
We can use the random number generator to pick a random item from an array. The following code snippet has an array of author names (strings). We can pick a random author by generating a random number that is less than the number of items in the array and use the random index to pick a random author name in the string.
The Random.Next method generates a random integer and by passing the maximum length of the array means the random number cannot be greater than the number of items in the array.
using System;
public class RandomStringInArraySample
{
public static void Main()
{
// A array of authors
string[] authors = { "Mahesh Chand", "Jeff Prosise", "Dave McCarter", "Allen O'neill",
"Monica Rathbun", "Henry He", "Raj Kumar", "Mark Prime",
"Rose Tracey", "Mike Crown" };
// Create a Random object
Random rand = new Random();
// Generate a random index less than the size of the array.
int index = rand.Next(authors.Length);
// Display the result.
Console.WriteLine($"Randomly selected author is {authors[index]}");
Console.ReadKey();
}
}
Figure 1
Figure 2
Summary
In this article and code snippet, we discussed how to select a random string from an array of strings.

Ashley PapePosted Apr 10, 2020, 11:05 AM
How can you make a NON random selection from an array?
Alish SafarliPosted May 18, 2019, 7:24 PM
Label1.Text = ""; Random ran = new Random(); Random ran2 = new Random(); string[] names = new string[7]; names[0] = "Alish"; names[1] = "Fuad"; names[2] = "Rashad"; names[3] = "Miri"; names[4] = "Faxri"; names[5] = "Ferid"; names[6] = "Sabrin"; int a = ran.Next(names.Length); int b = ran2.Next(names.Length); for (int i = 0; i < names.Length; i++) { label1.Text = names[a]; if (names[a] != names[b]) { label2.Text = names[b]; } }
Alish SafarliPosted May 18, 2019, 7:23 PM
How can show two different randoms in labels? but in condition they are not shown same
Sundaram SubramanianPosted Sep 11, 2018, 2:51 AM
Understood the basic concept behind the Random method. Much informative, thanks for this article
Saineshwar BageriPosted Sep 10, 2018, 8:57 AM
Sir Random is not Random always, there are Issues related to it link supporting answer :- https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number