c# 集合中有数字、字符的Orderby排序

string[] things= new string[] { "105", "101", "102", "103", "90","a","B" ,"A","b"};
foreach (var thing in things.OrderBy(x => x))
{
    Console.WriteLine(thing);
}
输出: 101,102,103,105,90,a,A,b,B
目标输出: 90,101,102,103,105,a,A,b,B
 

    foreach (var thing in things.OrderBy(x => x, new SemiNumericComparer()))
    {    
        Console.WriteLine(thing);
    }
 

 

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, false);
    }
    public static bool IsNumeric(object value)
    {
        try {
            int i = Convert.ToInt32(value.ToString());
            return true; 
        }
        catch (FormatException) {
            return false;
        }
    }
}

 

你可能感兴趣的