我确信这很简单,但我很难过。我希望,简化,对我的字母表进行排序,但将Ds放在As和B之间。我想我想要一个自定义IComparer来做到这一点。
如何完成此IComparer实现以通过我的断言?如果x是< IComparer文档说,返回小于0。 y,但重要的是多少小于零?抓我的头。
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);
}
}
答案 0 :(得分:2)
但重要的是少于零
不,完全没有。
基本上每次比较都必须从三个选项中得出一个结果:
所以要使“D”介于“A”和“B”之间,你会使用类似的东西:
public int Compare(string x, string y)
{
if (x == y)
{
return 0;
}
if (x == "D")
{
// Unless y is *actually* "B", we can just
// pretend that x is "B". (So it will be after any "A", but before
// any other "Bxyz".)
if (y == "B")
{
return -1;
}
return "B".CompareTo(y);
}
// Ditto, basically. Alternatively you could call Compare(y, x)
// and invert the result, but *don't* just negate it, as it does the
// wrong thing with int.MinValue...
if (x == "D")
{
if (x == "B")
{
return 1;
}
return x.CompareTo("B");
}
return x.CompareTo(y);
}
答案 1 :(得分:0)
使用Linq修改排序顺序会更容易:
letters.OrderBy(x=>EvaluationFunction(x));
实际EvaluationFunction
取决于您对排序的实际业务要求。
你看的订单对我来说没有多大意义,我无法猜测规则(为什么“D”在那里?)但是如果订单是A1,A2,B1,B2,C ,D,E
您的EvaluationFunction可以是:
string EvaluationFunction(string s){
return string.Format("{0,-3}", s); // pads s on the left with spaces, up to 3
}