List Sort メソッドがソートを処理する方法に問題があります。次の要素があるとします。
class Element : IComparable<Element>
{
public int Priority { get; set; }
public string Description { get; set; }
public int CompareTo(Element other)
{
return Priority.CompareTo(other.Priority);
}
}
このように並べ替えようとすると、次のようになります。
List<Element> elements = new List<Element>()
{
new Element()
{
Priority = 1,
Description = "First"
},
new Element()
{
Priority = 1,
Description = "Second"
},
new Element()
{
Priority = 2,
Description = "Third"
}
};
elements.Sort();
次に、最初の要素は、前の 2 番目の要素「Second」です。または、言い換えると、このアサーションは失敗します。
Assert.AreEqual("First", elements[0].Description);
要素が本質的に同じであるのに、.NET がリストを並べ替えるのはなぜですか? 比較でゼロ以外の値が返された場合にのみ、リストを並べ替えたいと思います。