用字符串实现自定义IComparer

例如,我在c#中有一组字符串;

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

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

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

这可能是使用I ComparerCompare(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 = 0 && index_y >= 0) { if (index_x < index_y) { return -1; } else return 1; } return 0; } 

这应该做你想要的:

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

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

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

输出:

b
C

1
Ë
一个
d
FOO

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