使用"for循环"将哈希表中的数据传递到C#中的列表框

scy*_*lla 1 c#

我一直在关注这个C#教程,发现它只描述了使用哈希表将数据传递给列表框foreach loop.

我想使用a传递哈希表中的数据for loop.到目前为止,这是我的代码.

    private void button1_Click(object sender, EventArgs e)
    {
        Hashtable students = new Hashtable();

        students.Add("Peter", 67);
        students.Add("Brayan", 76);
        students.Add("Lincoln", 56);
        students.Add("Jack", 65);
        students.Add("Mahone", "no score");
        students.Add("Kevin", 64);

        for (int i = 0; i < students.Count; i++)
        {
            listBox1.Items.Add(students[i]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

在此输入图像描述

Count methodfor loop工作中collections.for loop将哈希表数据传递到列表框时的正确方法是什么.

mat*_*mmo 5

你应该使用a Dictionary而不是a HashTable,你也应该使用a foreach来简化事情,然后你可以这样做:

private void button1_Click(object sender, EventArgs e)
{
    Dictionary<string, int> students = new Dictionary<string, int>();

    students.Add("Peter", 67);
    students.Add("Brayan", 76);
    students.Add("Lincoln", 56);
    students.Add("Jack", 65);
    students.Add("Mahone", 0);
    students.Add("Kevin", 64);

    foreach (var student in students)
    {
        listBox1.Items.Add(student.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意我用0代替"没有分数"(感谢Viper)

  • @IlyaIvanov是的会吗?`var`是动态类型.显式输入实际上是一个`KeyValuePair` (2认同)
  • @mattytommo不,它不会因为`var'而不是xD但是'no score'是一个字符串而你的`Dictionary <string,int>`等待一个`int` ..但它是OP的代码 (2认同)