使用数组对列表框中的项进行排序

本文关键字:排序 数组 列表 | 更新日期: 2023-09-27 18:04:36

Ok,所以我必须使用数组(defaultArray)为大学排序listbox (randomListBox),但说明和导师没有多大帮助,所以这就是我使用说明的内容,但它不起作用。

    string[] defaultArray = new string[randomListBox.Items.Count];
    for (int i = 0; i < randomListBox.Items.Count; i++)
    {
        defaultArray[i] = randomListBox.Items[i].ToString();
    }
    Array.Sort(defaultArray);
    randomListBox.Items.Clear();
    for (int i = 0; i < randomListBox.Items.Count; i++)
    {
        randomListBox.Items.Add(defaultArray[i].ToString());
    }

使用数组对列表框中的项进行排序

你的第二个for循环永远不会运行,因为你已经删除了listbox中的所有项目,因此项目计数是0。试一试:

for (int i = 0; i < defaultArray.Length; i++)
{
    randomListBox.Items.Add(defaultArray[i]);
}

考虑这一行的第二次出现:

for (int i = 0; i < randomListBox.Items.Count; i++)

你确定你是这个意思吗?

你真正想要循环的是什么?

(我不会直接给出答案,因为这是一个家庭作业问题)

在最后一个for循环中,您使用的是randomListBox.Items.Count而不是defaularray . length .

for (int i = 0; i < defaultArray.Length; i++)
{
    randomListBox.Items.Add(defaultArray[i].ToString());
}