将其描述为婴儿级别,以便初学者...
static void Main(string[] args)
{
string[] Names = { "Erik", "Levente", "Noel", "Áron", "Krisztián", "Kristóf", "Bence", "Roland", "Máté", "László", "Bálint" ,
"Regina", "Brigitta", "Gréta", "Hédi", "Hanna", "Boglárka", "Jázmin", "Réka", "Alexandra", "Rebeka", "Lili", "Luca", "Zsófi"};
List<string> alreadyUsed = new List<string>();
Random r = new Random();
while (alreadyUsed.Count < Names.Length)
{
int index = r.Next(0, Names.Length);
if (!alreadyUsed.Contains(Names[index]))
alreadyUsed.Add(Names[index]);
Console.WriteLine("The 1st Winner is: " + Names[r.Next(0, Names.Length - 1)]);
}
Console.ReadKey(true);
}
答案 0 :(得分:2)
如果您只想显示不重复的结果,请尝试:
while (alreadyUsed.Count < Names.Length)
{
int index = r.Next(0, Names.Length);
if (!alreadyUsed.Contains(Names[index]))
{
alreadyUsed.Add(Names[index]);
Console.WriteLine("The 1st Winner is: " + Names[index]);
}
}
请注意,在Console.WriteLine
中,我使用的是当前添加的项目Names[index]
,而不是Names[r.Next(0, Names.Length - 1)]
答案 1 :(得分:0)
也许此版本增加了可读性:
while (alreadyUsed.Count < Names.Length)
{
var notUsedYet = Names.Except(alreadyUsed).ToArray();
var index = r.Next(0, notUsedYet.Length);
alreadyUsed.Add(notUsedYet[index]);
Console.WriteLine("The 1st Winner is: " + notUsedYet[index]);
}