Implementing custom IComparer with string

后端 未结 2 460
旧巷少年郎
旧巷少年郎 2020-12-01 23:46

I have a collection of strings in c#, for example;

var example = new string[]{\"c\", \"b\", \"a\", \"d\"};

I then with to sort this, but my

2条回答
  •  星月不相逢
    2020-12-02 00:04

    This should do what you want:

    var example = new string[]{"c", "a", "d", "b"};
    var comparer = new CustomStringComparer(StringComparer.CurrentCulture);
    Array.Sort(example, comparer);
    
    ...
    
    class CustomStringComparer : IComparer
    {
        private readonly IComparer _baseComparer;
        public CustomStringComparer(IComparer baseComparer)
        {
            _baseComparer = baseComparer;
        }
    
        public int Compare(string x, string y)
        {
            if (_baseComparer.Compare(x, y) == 0)
                return 0;
    
            // "b" comes before everything else
            if (_baseComparer.Compare(x, "b") == 0)
                return -1;
            if (_baseComparer.Compare(y, "b") == 0)
                return 1;
    
            // "c" comes next
            if (_baseComparer.Compare(x, "c") == 0)
                return -1;
            if (_baseComparer.Compare(y, "c") == 0)
                return 1;
    
            return _baseComparer.Compare(x, y);
        }
    }
    

提交回复
热议问题