比较字符串

例子,当遇到A1 A10 A2 order by 不起作用了

需要自己写

public class StringCompare<T> : IComparer<T> where T : T_TempActicle
    {
        //比较两个字符串,如果含用数字,则数字按数字的大小来比较。
        int IComparer<T>.Compare(T x, T y)
        {
            if (x == null || y == null)
                throw new ArgumentException("Parameters can't be null");
            string fileA = x.Title as string;
            string fileB = y.Title as string;
            char[] arr1 = fileA.ToCharArray();
            char[] arr2 = fileB.ToCharArray();
            int i = 0, j = 0;
            while (i < arr1.Length && j < arr2.Length)
            {
                if (char.IsDigit(arr1[i]) && char.IsDigit(arr2[j]))
                {
                    string s1 = "", s2 = "";
                    while (i < arr1.Length && char.IsDigit(arr1[i]))
                    {
                        s1 += arr1[i];
                        i++;
                    }
                    while (j < arr2.Length && char.IsDigit(arr2[j]))
                    {
                        s2 += arr2[j];
                        j++;
                    }
                    try
                    {
                        if (Int64.Parse(s1) > Int64.Parse(s2))
                        {
                            return 1;
                        }
                        if (Int64.Parse(s1) < Int64.Parse(s2))
                        {
                            return -1;
                        }
                    }
                    catch
                    {
                        return 1;
                    }

                }
                else
                {
                    if (arr1[i] > arr2[j])
                    {
                        return 1;
                    }
                    if (arr1[i] < arr2[j])
                    {
                        return -1;
                    }
                    i++;
                    j++;
                }
            }
            if (arr1.Length == arr2.Length)
            {
                return 0;
            }
            else
            {
                return arr1.Length > arr2.Length ? 1 : -1;
            }
        }
    }

    public class T_TempActicle
    {
        public Guid ID { get; set; }
        public string Title { get; set; }
    }

 

posted @ 2014-07-28 16:40  haiziguo  阅读(279)  评论(0编辑  收藏  举报