如何在C#Array String中选择5位数随机?

时间:2012-11-16 10:33:46

标签: c#

  

可能重复:
  How can I generate random 8 character, alphanumeric strings in C#?

我有一个字母名称的数组。现在我需要随机选择5个字符。如果我使用下面的代码,我只能选择一个字符。 如何选择给定数组中的5个数字字符串随机?

    String[] letters = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q" };
    Random rand = new Random();
    String number = letters[rand.Next(1,10)];

3 个答案:

答案 0 :(得分:5)

string number = 
    string.Concat(Enumerable.Range(0,5).Select(i => 
        letters[rand.Next(0, 10)]));

当然,根据您的数组内容,这在功能上等同于:

string number = rand.Next(0, 100000).ToString("D5");

答案 1 :(得分:3)

string[] selected = new string[5];
Random rand = new Random();
for(int i = 0 ; i < selected.Length ; i++)
{
    selected[i] = letters[rand.Next(letters.Length)];
}

答案 2 :(得分:2)

var randomSelection = (from c in letters orderby rand.Next() select c).Take(5);