1

可能重复:
如何在 C# 中生成随机 8 个字符的字母数字字符串?

我有字母名称的数组。现在我需要随机选择 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)];
4

3 回答 3

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

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

string number = rand.Next(0, 100000).ToString("D5");
于 2012-11-16T10:37:04.727 回答
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)];
}
于 2012-11-16T10:36:15.223 回答
2
var randomSelection = (from c in letters orderby rand.Next() select c).Take(5);
于 2012-11-16T10:50:56.503 回答