我想生成 25 个唯一的随机数并将它们列在控制台中。数字应至少 10 个字符长。有什么简单的方法吗?
最佳答案
尝试将数字构建为字符串,并使用 HashSet 确保它们是唯一的:
Random random = new Random();
HashSet<string> ids = new HashSet<string>();
while (ids.Count < 25)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; ++i)
{
sb.Append(random.Next(10));
}
ids.Add(sb.ToString());
}
示例输出:
7895499338 2643703497 0126762624 8623017810 ...etc...
类(class)HashSet
出现在 .NET 3.5 和更新版本中。
关于c# - 生成多个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2942489/