需求描述:
有个listbox,里面的值是 110 10 70 40 260
但是设置sort=true的属性后,他的顺序就变为 10 110 260 40 70
如何做才能让它得到正确的顺序 10 40 70 110 260
这个listbox里的数字都是string型 而且不想让它变为int型
请问要如何做才对?
========================
结合IComparer接口实现排序:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] str = new string[] { "110", "10" ,"70" ,"40" ,"260" };
object[] data = Sort<string>(str);
listBox1.Sorted = false;//切记,一定为false
listBox1.DataSource = data;
}
object[] Sort<T>(T[] t)//自定义排序
{
double d=0.0;
ArrayList list = new ArrayList(t);
//实例化MyCompare
MyCompare com = new MyCompare();
list.Sort(com);
return list.ToArray();
}
}
class MyCompare : IComparer//自定义MyCompare类
{
private CaseInsensitiveComparer ObjectCompare;
public MyCompare()
{
ObjectCompare = new CaseInsensitiveComparer();
}
public int Compare(object x, object y)//比较大小
{
// 比较
double out1, out2;
if (double.TryParse(x.ToString(), out out1) && double.TryParse(y.ToString(), out out2))
return ObjectCompare.Compare(out1, out2);
else
{
// 如果相等返回0
return 0;
}
}
}