2016-01-03 59 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

相關問題