如何在C数组字符串中选择5位随机数?


How to select 5 digit random in C# Array String?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How can I generate random 8 character, alphanumeric strings in C#?

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

1
2
3
    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)];


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

当然,考虑到数组内容,这在功能上等同于:

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


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


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