排序要求:按数字、文字、字母、符号的优先顺序排序
未排序:
yyds
1
air
2
#30
10
第8号
13
azure
系统默认排序结果:
#30
1
10
13
2
air
azure
yyds
第8号
要求排序后:
1
2
10
13
第8号
air
azure
yyds
#30
private void StringSort()
{
List<string> list = new List<string>()
{
"azure",
"1",
"air",
"2",
"#30",
"10",
"第8号",
"13",
"yyds"
};
var sorted = list.OrderBy(o => o, MyComparer .Instance);
}
class MyComparer : IComparer<string>
{
public static readonly MyComparer Instance = new MyComparer();
public static readonly string RegexNum = @"^[0-9]+";
public static readonly string RegexHan = @"^[\u4e00-\u9fa5]+";
public static readonly string RegexLetter = @"^[A-Za-z]+";
public static readonly string RegexSymbol = @"^[^0-9A-Za-z\u4e00-\u9fa5]+";
public int Compare(string x, string y)
{
if (double.TryParse(x, out double xd) && double.TryParse(y, out double yd))
{
//均由数字组成的比较
return (int)(xd - yd);
}
else
{
bool xIsNum = Regex.IsMatch(x, RegexNum);
bool yIsNum = Regex.IsMatch(y, RegexNum);
bool xIsHan = Regex.IsMatch(x, RegexHan);
bool yIsHan = Regex.IsMatch(y, RegexHan);
bool xIsLetter = Regex.IsMatch(x, RegexLetter);
bool yIsLetter = Regex.IsMatch(y, RegexLetter);
bool xIsSymbol = Regex.IsMatch(x, RegexSymbol);
bool yIsSymbol = Regex.IsMatch(y, RegexSymbol);
if ((xIsNum && yIsNum) || (xIsHan && yIsHan) || (xIsLetter && yIsLetter) || (xIsSymbol && yIsSymbol))
{
//同样的字符开头,则正常比较
return string.Compare(x, y);
}
else
{
//以数字、文字、字母、符号排序
if (xIsNum)
{
return -1;
}
else if (yIsNum)
{
return 1;
}
else if (xIsHan)
{
return -1;
}
else if (yIsHan)
{
return 1;
}
else if (xIsLetter)
{
return -1;
}
else if (yIsLetter)
{
return 1;
}
else if (xIsSymbol)
{
return -1;
}
else if (yIsSymbol)
{
return 1;
}
return string.Compare(x, y);
}
}
}
}