【发布时间】:2019-12-06 20:53:26
【问题描述】:
我的列表定义为:
List<string> firstNames = new List<string>();
当我向这个列表中添加一些字符串时,我将如何从列表中检索一个随机字符串?比如:
string currName = someFunctionOf (firstNames);
【问题讨论】:
-
加分 - 做一个扩展方法来做到这一点!
标签: c#
我的列表定义为:
List<string> firstNames = new List<string>();
当我向这个列表中添加一些字符串时,我将如何从列表中检索一个随机字符串?比如:
string currName = someFunctionOf (firstNames);
【问题讨论】:
标签: c#
这里有一种与发布的三个不同的方法,只是为了让 LINQ 更加多样化和有趣:
string aName = firstNames.OrderBy(s => Guid.NewGuid()).First();
【讨论】:
这样的?
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 ];
【讨论】:
试试这个
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];
【讨论】:
randNum.Next(firstNames.Count); 按预期工作。