方法实现
///<summary>
///主要用于字符串类型排序
///规则:1.如果字符串不是数字开头,且数字前存在不同字符,则按照不同字符前后决定排序
///规则:2.如果字符串不是数字开头,且数字前字符相同,则按照数字区域整体大小排序,若数字相同,则看后续字符比较
///规则:3.如果两个字符存在包含则按照数据长度对比
///</summary>
public class StringRankComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null || y == null)
{
throw new ArgumentException("Can't be null");
}
if (string.IsNullOrEmpty(x.Trim()) && !string.IsNullOrEmpty(y.Trim()))
{
return 1;
}
else if (!string.IsNullOrEmpty(x.Trim()) && string.IsNullOrEmpty(y.Trim()))
{
return -1;
}
else if (string.IsNullOrEmpty(x.Trim()) && string.IsNullOrEmpty(y.Trim()))
{
return 0;
}
char[] arr1 = x.ToCharArray();
char[] arr2 = y.ToCharArray();
int i = 0, j = 0;
while (i < arr1.Length && j < arr2.Length)
{
if (char.IsDigit(arr1[i]) && char.IsDigit(arr2[j]))
{
string s1 = "", s2 = "";
while (i < arr1.Length && char.IsDigit(arr1[i]))
{
s1 += arr1[i];
i++;
}
while (j < arr2.Length && char.IsDigit(arr2[j]))
{
s2 += arr2[j];
j++;
}
if (int.TryParse(s1, out int is1) && int.TryParse(s2, out int is2))
{
if (is1 > is2)
{
return 1;
}
if (is1 < is2)
{
return -1;
}
}
else
{
int result = string.Compare(s1, s2, true);
if (result != 0)
{
return result;
}
}
}
else
{
if (arr1[i] > arr2[j])
{
return 1;
}
else if (arr1[i] < arr2[j])
{
return -1;
}
i++;
j++;
}
}
return arr1.Length == arr2.Length ? 0 : arr1.Length > arr2.Length ? 1 : -1;
}
}
方法调用
List<string> rankList = new List<string>()
{
"ABC", "ABC1", "ABC2", "ABC03", "ABC120", "AB1", "AC1", "A1", "A", "ABC1A"
};
rankList.OrderBy(p => p, new StringRankComparer())
结果:{ "A", "A1", "AB1", "ABC", "ABC1", "ABC1A", "ABC2", "ABC03", "ABC120", "AC1" }