dhalberg
dhalberg

Reputation: 155

How could I get a random string from a list and assign it to a variable

My list is defined as:

List<string> firstNames = new List<string>();

When I add some strings to this list, how would I go about retrieving a random string from the list? Something like:

string currName = someFunctionOf (firstNames);

Upvotes: 7

Views: 33056

Answers (3)

mkedobbs
mkedobbs

Reputation: 4375

Here's a different approach than the three posted, just for some variety and fun with LINQ:

string aName = firstNames.OrderBy(s => Guid.NewGuid()).First();

Upvotes: 26

RRUZ
RRUZ

Reputation: 136391

try this

    List<string> firstNames = new List<string>();
    firstNames.Add("name1");
    firstNames.Add("name2");
    firstNames.Add("name3");
    firstNames.Add("namen");

    Random randNum = new Random();
    int aRandomPos = randNum.Next(firstNames.Count);//Returns a nonnegative random number less than the specified maximum (firstNames.Count).

    string currName = firstNames[aRandomPos];

Upvotes: 9

Ed Swangren
Ed Swangren

Reputation: 124642

Something like this?

List<string> myList = new List<string>( );
// add items to the list
Random r = new Random( );
int index = r.Next( myList.Count );
string randomString = myList[ index ];

Upvotes: 17

Related Questions