在这种情况下,我如何显示没有重复的结果?

时间:2018-07-31 09:16:07

标签: c# random names

将其描述为婴儿级别,以便初学者...

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);
}

2 个答案:

答案 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]);
}