csharp C#數字字符串排序orderby的問題解決

 

   通常狀況下 您使用 網絡

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);
}

 

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;
                }
            }
        }

  

代碼摘自網絡。spa

相關文章
相關標籤/搜索