无法隐式转换类型' int'到'字符串'我不能

时间:2016-01-03 16:26:14

标签: c# arrays

我有一个简单的问题。 dizi是一个字符串数组。我无法用数字对它进行排序。

我想按数字排序。

string[] dizi = new string[40];

for (int i = 0; i < listBox1.Items.Count; i++) {
    dizi[i] = listBox1.Items[i].ToString();
}

Array.Sort(dizi);
label2.Text = dizi[0];

2 个答案:

答案 0 :(得分:3)

我认为你想要的是通过将listbox项放入Array来对它们进行排序,但与此同时,你也将listbox项更改为{的数组{1}}和string无法按string降序/升序排序

在这种情况下,您应该将intlistbox作为Array的{​​{1}},然后将其排序为int,然后再将其显示在int中作为Label

string

这样,int[] dizi = new int[listBox1.Items.Count]; //here is int array instead of string array, put generic size, just as many as the listBox1.Items.Count will do for (int i = 0; i < listBox1.Items.Count; i++) { dizi[i] = Convert.ToInt32(listBox1.Items[i].ToString()); //assuming all your listBox1.Items is in the right format, the above code shall work smoothly, //but if not, use TryParse version below: // int listBoxIntValue = 0; // bool isInt = int.TryParse(listBox1.Items[i].ToString(), out listBoxIntValue); //Try to parse the listBox1 item // if(isInt) //if the parse is successful // dizi[i] = listBoxIntValue; //take it as array of integer element, rather than string element. Best is to use List though //here, I put the safe-guard version by TryParse, just in case the listBox item is not necessarily valid number. //But provided all your listBox item is in the right format, you could easily use Convert.ToInt32(listBox1.Items[i].ToString()) instead } Array.Sort(dizi); //sort array of integer label2.Text = dizi[0].ToString(); //this should work 就是您dizi项的排序版本listbox1。每当您需要int时,只需使用string作为数组元素

另外,作为附注:考虑使用ToString() Listint来获取int.TryParse中的整数元素值,以防您不确定是否由于某种原因,所有listBox.Items都可以转换为listBox.Items

答案 1 :(得分:1)

从列表框中删除时转换为整数

int[] dizi = new int[40];
for (int i = 0; i < listBox1.Items.Count; i++) {
     dizi[i] = Convert.toInt32(listBox1.Items[i].ToString());
     }

Array.Sort(dizi);
label2.Text= Convert.toString(dizi[0]);