C# 如何从列表中获取随机字符串并将其分配给变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1753508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How could I get a random string from a list and assign it to a variable
提问by dhalberg
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);
回答by Ed S.
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 ];
回答by RRUZ
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];
回答by mkedobbs
Here's a different approach than the three posted, just for some variety and fun with LINQ:
这是一种与发布的三种方法不同的方法,只是为了 LINQ 的一些多样性和乐趣:
string aName = firstNames.OrderBy(s => Guid.NewGuid()).First();