Implementing custom IComparer with string

后端 未结 2 457
旧巷少年郎
旧巷少年郎 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:17

    A simple way is to substitute integers for the strings.

    class MyComparer : IComparer
    {
        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 { "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.

提交回复
热议问题