从列表中删除随机项目 C#

Removing a random item from a list C#

我的第一个问题就在这里。 我正在尝试使用按钮和列表制作匹配游戏。我使用列表用字母表示图像,当使用字母时,它应该从列表中删除该字母,从而减少列表中的项目数。但是我收到错误索引超出范围。任何帮助将不胜感激。 提前致谢, 里斯

 Random random = new Random();

    List<string> icons = new List<string>() 
{ 
    "!", "!", "N", "N", ",", ",", "k", "k",
    "b", "b", "v", "v", "w", "w", "z", "z"
};


    Button[,] btn = new Button[4, 4];
    //Random r = new Random();            // Random variable
    public GameWindow()
    {
        InitializeComponent();

        for (int x = 0; x < 4; x++)
        {

            for (int y = 0; y < 4; y++)
            {

                btn[x, y] = new Button();
                btn[x, y].SetBounds(80 * x, 80 * y, 80, 80);
                btn[x, y].FlatAppearance.BorderSize = 1;
                btn[x, y].Click += new EventHandler(this.btnEvent_Click);
                btn[x, y].BackColor = System.Drawing.ColorTranslator.FromHtml("#35014F");
                Controls.Add(btn[x, y]);
                btn[x, y].Font = new Font("Webdings", 50, FontStyle.Regular);
                AssignIconsToButtons(btn[x, y]);




            }
        }

    }


    void AssignIconsToButtons(Button ButtonToAssign)
    {
        foreach (Button control in this.Controls)
        {

            Button iconButton = control as Button;

            if (iconButton != null)
            {


                int randomNumber = random.Next(icons.Count);
                //MessageBox.Show(Convert.ToString(randomNumber));
                iconButton.Text = icons[randomNumber];
                //iconButton.ForeColor = iconButton.BackColor;
                icons.RemoveAt(randomNumber);

            }

您的随机数生成应该是:

int randomNumber = random.Next(icons.Count-1);

这是因为您的数组从 0 开始,计数告诉您列表中的对象数。

这样试试:(Random.Next(Int32, Int32))

if (iconButton != null && icons.Count > 0)
{
    int randomNumber = random.Next(0, icons.Count);
    //MessageBox.Show(Convert.ToString(randomNumber));
    iconButton.Text = icons[randomNumber];
    //iconButton.ForeColor = iconButton.BackColor;
    icons.RemoveAt(randomNumber)
}

感谢 NeverHopeless 的工作,现在我的屏幕上只显示了四张图片 盒子而不是 16,编码的乐趣,感谢您的帮助。

  if (iconButton != null && icons.Count > 0)
     {


int randomNumber = random.Next(0, icons.Count-1);
//MessageBox.Show(Convert.ToString(randomNumber));
iconButton.Text = icons[randomNumber];
//iconButton.ForeColor = iconButton.BackColor;
icons.RemoveAt(randomNumber)
  }