c# 自定义字符串排序
场景:List 需要按照某字段属性排序
字段数据存在如1,2,F1,F2,楼层3,F3,楼层11,
需要按照1,2,F1,F2,F3,楼层3,楼层11 来排序
public class NumericStringComparer : IComparer<string>
{
public static readonly NumericStringComparer Instance = new NumericStringComparer();
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);
}
}
}
}
示例:
list.OrderBy(s => s.Name, new NumericStringComparer());