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<strin开发者_如何学运维g>();
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);
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 ];
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];
精彩评论