IComparer 自定义 比较

来源:互联网 发布:网络安全工程师多少钱 编辑:程序博客网 时间:2024/06/05 10:20

先说需求 把一数字字符串(例“123”)按数字排序 

“1”,“02”,“21” ,“3”,“11”,“10”,“a-1”

排序数字排序后为

“1”,“02”,“3”,“10”,“11”,“21” ,“a-1”


    public class MySort : IComparer<string>    {        int IComparer<string>.Compare(string x, string y)        {            return Compare(x, y);        }        private int Compare(string x, string y)        {            int a = 0;            int b = 0;            if (Int32.TryParse(Path.GetFileNameWithoutExtension(x), out a) && Int32.TryParse(Path.GetFileNameWithoutExtension(y), out b))            {                int c = a - b;                if (c == 0)                {                    return string.Compare(x, y, true);                }                return c;            }            else            {                return string.Compare(x, y, true);            }        }    }

之前用了 try catch 做判断 速度 就慢了许多

    public class MySort : IComparer<string>    {        int IComparer<string>.Compare(string x, string y)        {            return Compare(x, y);        }        private int Compare(string x, string y)        {            try            {                int a = Convert.ToInt32(Path.GetFileNameWithoutExtension(x));                int b = Convert.ToInt32(Path.GetFileNameWithoutExtension(y));                int c = a - b;                if (c == 0)                {                    return string.Compare(x, y, true);                }                return c;            }            catch (Exception)            {                return string.Compare(x, y, true);            }        }    }



0 0
原创粉丝点击