2016-01-03 55 views
-6

我有一个简单的问题。 dizi是一个字符串数组。我无法对int进行数字排序。我想排序为数组数组。无法将类型'int'隐式转换为'字符串'。我不能

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]; 
+1

哪一行会在标题中引发错误? – David

+1

为什么它错了? – Ian

+1

请参见[编写完美问题](http://tinyurl.com/stack-hints)。 – HABO

回答

3

我想你想要的是将它们放入一个Arraylistbox项目进行排序,但在同一时间,你也改变了listbox项目进入stringstring阵列无法通过升/降作为int确实

在这种情况下进行排序,你倒是应该让你[R listbox项目为intArray,然后在你的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 

这样才排序为intdizi会为你listbox1项排序的版本int。当你需要以此为string只使用ToString()的数组元素

此外,作为一个侧面说明:考虑使用intListint.TryParse来从listBox.Items万一整数元素值的你不知道是否所有的由于某种原因,listBox.Items可能会转换为int

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

我没有使用toInt32(...) –

+0

我添加它为您解决您的问题。 – nicomp

相关问题