先说需求 把一数字字符串(例“123”)按数字排序
“1”,“02”,“21” ,“3”,“11”,“10”,“a-1”
排序数字排序后为
“1”,“02”,“3”,“10”,“11”,“21” ,“a-1”
public class MySort : IComparer<string>
{
int IComparer<string>.Compare(string x, string y)
{
return Compare(x, y);
}
private int Compare(string x, string y)
{
int a = 0;
int b = 0;
if (Int32.TryParse(Path.GetFileNameWithoutExtension(x), out a) && Int32.TryParse(Path.GetFileNameWithoutExtension(y), out b))
{
int c = a - b;
if (c == 0)
{
return string.Compare(x, y, true);
}
return c;
}
else
{
return string.Compare(x, y, true);
}
}
}
之前用了 try catch 做判断 速度 就慢了许多
public class MySort : IComparer<string>
{
int IComparer<string>.Compare(string x, string y)
{
return Compare(x, y);
}
private int Compare(string x, string y)
{
try
{
int a = Convert.ToInt32(Path.GetFileNameWithoutExtension(x));
int b = Convert.ToInt32(Path.GetFileNameWithoutExtension(y));
int c = a - b;
if (c == 0)
{
return string.Compare(x, y, true);
}
return c;
}
catch (Exception)
{
return string.Compare(x, y, true);
}
}
}