在这种情况下,我如何在没有复制的情况下显示结果?:)
In this situation how can i display the results without duplicatin ?:)
在婴儿级别描述它,我是新手...
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);
}
如果您只想显示结果而不重复,请尝试:
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)]
也许这个版本增加了一些可读性:
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]);
}
在婴儿级别描述它,我是新手...
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);
}
如果您只想显示结果而不重复,请尝试:
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)]
也许这个版本增加了一些可读性:
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]);
}