我敢肯定这很简单,但它让我很难过。我想简化地对我的字母进行排序,但将 Ds 放在 As 和 Bs 之间。我想我想要一个自定义的 IComparer 来做到这一点。
我将如何完成这个 IComparer 实现以传递我的断言?IComparer 文档说,如果 x < y,则返回小于 0,但是小于零有关系吗?抓着我的头。
private static void Main(string[] args)
{
var letters = new List<string> { "A2", "E", "B1", "A1", "D", "C", "B2" };
var sorted = new List<string> { "A1", "A2", "D", "B1", "B2", "C", "E" };
letters.Sort(new MyComparer());
Assert.IsTrue(letters.SequenceEqual(sorted));
}
/// <summary>
/// Sorts D between A and B
/// </summary>
private class MyComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (string.Equals(x, "D"))
{
// return what?
}
return string.CompareOrdinal(x, y);
}
}