Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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);
like image 223
dhalberg Avatar asked Nov 18 '09 03:11

dhalberg


People also ask

How do you get a random string from a list in Python?

In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.

How do you assign a random string in Python?

In order to generate random strings in Python, we use the string and random modules. The string module contains Ascii string constants in various text cases, digits, etc. The random module on the other hand is used to generate pseudo-random values.

How do you pick a random value from a list in Python?

Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.

How do you generate random strings?

A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer.


2 Answers

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();
like image 176
mkedobbs Avatar answered Sep 21 '22 16:09

mkedobbs


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 ];
like image 30
Ed S. Avatar answered Sep 22 '22 16:09

Ed S.