How to create custom common number-text comparer i

2019-09-14 07:35发布

I have number-text list and I want to create common custom comparer logic to sort this list(s) using C#. E.g.

var numericList = new List<string>{"100", "--", "-0.98", "N/A", "0.00", "-888"};
var stringList = new List<string> {"Smith", "--", "Peter", "", "Jim", "Ken", "NA"};

which contains some special characters like --, N/A,Space etc. And expected result after sort will be - For NemericList Ascending -> N/A, -- , -888 , -0.98 , 0.00 , 100 For StringList Ascending -> Jim, Ken, N/A, Peter, Smith, Empty, --

I created following custom comparer logic which does some level of sorting but not matching with the expected result. Please suggest me the way to achieve this.

public class NumberTextComparer : IComparer<string>
    {
        public int Compare(string s1, string s2)
        {
            double number1, number2;
            var isS1Numeric = double.TryParse(s1, out number1);
            var isS2Numeric = double.TryParse(s2, out number2);

            if (isS1Numeric && isS2Numeric)
            {
                if (number1 > number2) return 1;
                if (number1 < number2) return -1;
                return 0;
            }

            return isS1Numeric ? 1 : (isS2Numeric ? -1 : String.Compare(s1, s2, StringComparison.OrdinalIgnoreCase));
        }
    }
var comparer = new NumberTextComparer();
var numericSortedListASC = numericList.OrderBy(str => str, comparer);
var stringSortedListASC = stringList.OrderBy(str => str, comparer);

1条回答
贪生不怕死
2楼-- · 2019-09-14 08:19

Your code works correct. Se here. Results:

--, N/A, -888, -0.98, 0.00, 100
, --, Jim, Ken, NA, Peter, Smith

The problem is your assumption, that the "" and "--" come after letters. Since they have a lower position in the ascii-table they come first.

This would be a simple fix. Try here

    public int Compare(string s1, string s2)
    {
        double number1, number2;
        var isS1Numeric = double.TryParse(s1, out number1);
        var isS2Numeric = double.TryParse(s2, out number2);

        if (isS1Numeric && isS2Numeric)
        {
            if (number1 > number2) return 1;
            if (number1 < number2) return -1;
            return 0;
        }
        if (isS1Numeric)
            return 1;
        if (isS2Numeric)
            return -1;

        bool s1StartsWithLetter = char.IsLetter(s1.FirstOrDefault());
        bool s2StartsWithLetter = char.IsLetter(s2.FirstOrDefault());

        if (s1StartsWithLetter == s2StartsWithLetter)
            return String.Compare(s1, s2, StringComparison.OrdinalIgnoreCase);
        return s1StartsWithLetter ? -1 : 1;
    }
查看更多
登录 后发表回答