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

在婴儿级别描述它,我是初学者......


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

}


不负相思意
浏览 202回答 2
2回答

繁花如伊

如果您只想显示没有重复的结果,请尝试:while (alreadyUsed.Count < Names.Length){&nbsp; &nbsp; int index = r.Next(0, Names.Length);&nbsp; &nbsp; if (!alreadyUsed.Contains(Names[index]))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; alreadyUsed.Add(Names[index]);&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("The 1st Winner is:&nbsp; " + Names[index]);&nbsp; &nbsp; }}请注意,在Console.WriteLine我使用当前添加的项目Names[index]而不是Names[r.Next(0, Names.Length - 1)]

茅侃侃

也许这个版本增加了一些可读性:while (alreadyUsed.Count < Names.Length){&nbsp; &nbsp; var notUsedYet = Names.Except(alreadyUsed).ToArray();&nbsp; &nbsp; var index = r.Next(0, notUsedYet.Length);&nbsp; &nbsp; alreadyUsed.Add(notUsedYet[index]);&nbsp; &nbsp; Console.WriteLine("The 1st Winner is:&nbsp; " + notUsedYet[index]);}
打开App,查看更多内容
随时随地看视频慕课网APP