0

これは簡単だと思いますが、困惑しています。単純化して、アルファベットを並べ替えたいのですが、A と B の間に D を入れます。これを行うには、カスタム IComparer が必要だと思います。

アサーションを渡すには、この IComparer の実装をどのように仕上げればよいでしょうか? IComparer のドキュメントには、x が < y の場合は 0 未満を返すと書かれていますが、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);
    }
}
4

2 に答える 2

2

しかし、ゼロよりどれだけ小さいかは重要ですか

いいえ、まったくありません。

基本的に、各比較では、3 つのオプションから 1 つの結果が得られる必要があります。

  • 最初の値が 2 番目の値より小さい
  • 値が等しい
  • 最初の値が 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);
}
于 2013-03-22T18:59:17.220 に答える
1

Linq を使用して並べ替え順序を変更する方が簡単です。

letters.OrderBy(x=>EvaluationFunction(x));

実際EvaluationFunctionは、並べ替えに関する実際のビジネス要件によって異なります。

あなたが見ている順序は私にはあまり意味がありません.ルールを推測することはできません.え

EvaluationFunction は次のようになります。

string EvaluationFunction(string s){
    return  string.Format("{0,-3}", s); // pads s on the left with spaces, up to 3
}
于 2013-03-22T19:07:06.820 に答える