19

例如,我在 c# 中有一个字符串集合;

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

然后我对此进行排序,但我的 IComparer 方法不起作用,并且看起来无限循环。

基本上我需要"b"先来,然后是"c",然后我不在乎其他任何人的顺序。

这可能使用 IComparer<string>Compare(string x, string y)方法吗?

编辑:代码

    public int Compare(string x, string y)
    {
        var sOrder = new string[] { "b", "c" };
        int index_x = -1;
        int index_y = -1;

        for (int i = 0; i < sOrder.Length;i++)
        {
            if (sOrder[i] == x)
                index_x = i;
            else if (sOrder[i] == y)
                index_y = i;
        }

        if (index_x >= 0 && index_y >= 0)
        {
            if (index_x < index_y)
            {
                return -1;
            }
            else
                return 1;
        }
        return 0;
    }
4

2 回答 2

30

这应该做你想要的:

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);
    }
}
于 2012-01-23T17:23:29.703 回答
7

一种简单的方法是用整数代替字符串。

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);

输出:

b
c

1
e
a
d
foo

请注意,这不是一个稳定的排序。如果您需要稳定的排序,则需要做更多的工作。

于 2012-01-23T17:27:36.497 回答