我有一個簡單的問題。 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];
我有一個簡單的問題。 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];
我想你想要的是將它們放入一個Array
到listbox
項目進行排序,但在同一時間,你也改變了listbox
項目進入string
和string
陣列無法通過升/降作爲int
確實
在這種情況下進行排序,你倒是應該讓你[R listbox
項目爲int
Array
,然後在你的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
這樣才排序爲int
,dizi
會爲你listbox1
項排序的版本int
。當你需要以此爲string
只使用ToString()
的數組元素
此外,作爲一個側面說明:考慮使用int
List
和int.TryParse
來從listBox.Items
萬一整數元素值的你不知道是否所有的由於某種原因,listBox.Items
可能會轉換爲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]);
我沒有使用toInt32(...) –
我添加它爲您解決您的問題。 – nicomp
哪一行會在標題中引發錯誤? – David
爲什麼它錯了? – Ian
請參見[編寫完美問題](http://tinyurl.com/stack-hints)。 – HABO