如何从列表中获取随机字符串并将其分配给变量

时间:2009-11-18 03:50:56

标签: c#

我的列表定义为:

List<string> firstNames = new List<string>();

当我在此列表中添加一些字符串时,如何从列表中检索随机字符串?类似的东西:

string currName = someFunctionOf (firstNames);

3 个答案:

答案 0 :(得分:19)

这里有一个与发布的三个不同的方法,只是为了LINQ的一些变化和乐趣:

string aName = firstNames.OrderBy(s => Guid.NewGuid()).First();

答案 1 :(得分:14)

这样的东西?

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 ];

答案 2 :(得分:6)

试试这个

    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];