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