我一直在关注这个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 method在for loop工作中collections.for loop将哈希表数据传递到列表框时的正确方法是什么.
你应该使用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)