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);
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.
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.
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.
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.
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();
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 ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With