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

  

代码摘自网络。

posted @ 2019-03-04 10:58  iDEAAM  阅读(3567)  评论(1编辑  收藏  举报