Implementing custom IComparer with string

时光总嘲笑我的痴心妄想 提交于 2019-11-27 09:25:06

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<string>
{
    private readonly IComparer<string> _baseComparer;
    public CustomStringComparer(IComparer<string> 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);
    }
}
Igby Largeman

A simple way is to substitute integers for the strings.

class MyComparer : IComparer<string>
{
    public override int Compare(string x, string y)
    {
        int ix = x == "b" ? 0 : x == "c" ? 1 : 2;
        int iy = y == "b" ? 0 : y == "c" ? 1 : 2;
        return ix.CompareTo(iy);
    }
}

var example = new List<string> { "c", "b", "a", "d", "foo", "", "1", "e"};
example.Sort(new MyComparer());
foreach (var s in example)
    Console.WriteLine(s);

Output:

b
c

1
e
a
d
foo

Note that this isn't a stable sort. If you need a stable sort, there's a little more work involved.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!