Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c# - Implementing custom IComparer with string

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 IComparer method is not working, and looping infinitely by the seems of things.

Basically I need "b" to come first, followed by "c", then I dont care about the order of any of the others.

Is this possible using IComparer<string> and the Compare(string x, string y) method?

Edit: Code

    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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...