2

Having trouble adding integers to the item array of a list box. Cannot seem to convert the listbox to integer.

int[] ratingArray = new int[numberRatingsInt];
for (int i = 0; i < numberRatingsInt; i++)
{
    ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i]);
}
4

4 回答 4

2

添加.ToString()ratingListBox.Items[i]

它应该是:

int[] ratingArray = new int[numberRatingsInt];
for (int i = 0; i < ratingListBox.Items.Count; i++)
{
    ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i].ToString());
}

刚刚测试:

.value之后ratingListBox.Items[i]也可以工作。

它也可以像下面这样工作:

int[] ratingArray = new int[numberRatingsInt];
for (int i = 0; i < ratingListBox.Items.Count; i++)
{
    ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i].Value);
}

(这是参考@Chris 答案添加的测试。)

编辑:

放入ratingListBox.Items.Countfor循环条件。

于 2013-05-23T12:25:28.293 回答
2

ListBoxescontains ListItems,而不是直接的值。尝试这个:

 int[] ratingArray = new int[numberRatingsInt];
    for (int i = 0; i < numberRatingsInt; i++)
    {
        ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i].Value);
    }
于 2013-05-23T12:26:55.850 回答
2

只是为了添加其他答案,您还可以做一个性感的 lambda,例如:

int[] ratingArray = ratingListBox.Items.OfType<ListItem>()
                                 .Select(x => int.Parse(x.Value))
                                 .ToArray();

这应该摆脱所有循环计数、常量等。

于 2013-05-23T12:35:06.277 回答
1

请试试这个

var modarray = ratingListBox.Items.Cast<String>().ToArray();
int[] arr = modarray.Select(int.Parse).ToArray();
于 2013-05-23T12:44:43.027 回答