无法隐式转换类型';int';到';字符串'.我可以';t

本文关键字:int 我可以 字符串 转换 类型 | 更新日期: 2023-09-27 18:28:45

我有一个简单的问题。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];

无法隐式转换类型';int';到';字符串'.我可以';t

我认为您想要的是通过将listbox项放入Array来对其进行排序,但同时,您也将listbox项更改为string的数组,string不能像int那样按降序/升序进行排序

在这种情况下,您应该将listbox项目作为intArray,然后将其排序为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()用于数组元素

此外,请注意:考虑使用intint.TryParse中的ListlistBox.Items中获取整数元素值,以防您不确定是否所有的listBox.Items都可以转换为int

从列表框中删除时转换为int

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]);