【问题标题】:How can i use ' ++ i ' inside this situation?在这种情况下如何使用'++ i'?
【发布时间】:2018-07-31 12:19:24
【问题描述】:

我想为用户可以赢得由他们的 ID(1、2、3 等)指定的项目的事件绘制一个随机名称。随机名称部分现在还可以,但我怎样才能显示结果:

The ID : 1 winner is:  'the random name'
The ID : 2 winner is:  'the random name'
etc...
till ID : 27
    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 ID : 1  winner is:  " + Names[index]);
                }
            }
            Console.ReadKey(true);
        }

【问题讨论】:

  • 为什么特别想使用++i
  • 你没有一个名为i的变量,你到底想达到什么目的?
  • @Sayse 他试图在The ID : 1 winner is计数
  • 值得一提的是,您只有 24 个名字,但您想直到 ID:27

标签: c# list random draw


【解决方案1】:

这是一个重构的方法,没有那么糟糕的表现alreadyUsed。首先我随机化数组,其次我迭代并使用递增的索引/ id 显示每个项目。

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"};
Random r = new Random();
Names = Names.OrderBy(_ => r.Next()).ToArray();
for(int i=0;i< Names.Length;i++)
{
    Console.WriteLine("The ID : " + (i+1) + " winner is:  " + Names[i]);
}

【讨论】:

  • 为什么 7,LINQ 和 lambda 函数都是从 C# 3.0 开始出现的
  • @dlatikay 我的错,我弄糊涂了
【解决方案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 ID : " + alreadyUsed.Count + " winner is:  " + Names[index]);
    }
}

您不需要++i,您已经拥有包含在alreadyUsed.Count 中的位置,当您使用alreadyUsed.Add(...) 时该位置会自动增加。

Try it online

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2018-11-22
    • 2022-01-23
    • 2015-11-30
    • 2017-05-16
    • 2012-10-06
    • 2011-05-18
    • 2019-11-29
    • 2022-01-23
    相关资源
    最近更新 更多