Reputation: 155
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
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
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
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