一般情况下 您使用
strs.OrderBy(n=>n) 得出的结论是 1, 11,111,2,22,222
想要得出 1,2,11,22,111,222 咋办?
源码送上
static void Main()
{
SemiNumericComparer comp = new SemiNumericComparer();
List<string> strs = new List<string>(){"11", "12", "1:"};
foreach(string str in strs.OrderBy(n => n, comp))
Console.writeLine(str);
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class SemiNumericComparer : IComparer< string > { public int Compare( string s1, string s2) { if (IsNumeric(s1) && IsNumeric(s2)) { if (Convert.ToInt32(s1) > Convert.ToInt32(s2)) return 1; if (Convert.ToInt32(s1) < Convert.ToInt32(s2)) return -1; if (Convert.ToInt32(s1) == Convert.ToInt32(s2)) return 0; } if (IsNumeric(s1) && !IsNumeric(s2)) return -1; if (!IsNumeric(s1) && IsNumeric(s2)) return 1; return string .Compare(s1, s2, true ); } public static bool IsNumeric( object value) { try { int i = Convert.ToInt32(value.ToString()); return true ; } catch (FormatException) { return false ; } } } |