对于字符串列表,List<string> strList = new List<string>(new string[] { "1", "10", "2"}),
默认排序为:1,10,2
如果想得到1,2,10这样序列的排序结果,目前我所知道的有如下几种方法:
1.自定义比较器
代码
static void Main(string[] args)
{
List<string> strList = new List<string>(new string[] { "1", "10", "2"});
strList.Sort(new MyComparer());
foreach (string s in strList)
{
Console.WriteLine(s);
}
}
private class MyComparer : Comparer<string>
{
public override int Compare(string x, string y)
{
return int.Parse(x) - int.Parse(y);
}
}
2.委托
strList.Sort(delegate(string val1, string val2) { return Int32.Parse(val1).CompareTo(Int32.Parse(val2)); });
3.Linq
strList = strList.OrderBy(s => int.Parse(s)).ToList();