我有多么列表进行排序的方法处理排序的问题。考虑到以下因素:
I have a problem with how the List Sort method deals with sorting. Given the following element:
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();
那么第一个元素是previously第二个元素秒。或者,换句话说,这个断言失败:
Then the first element is the previously second element "Second". Or, in other words, this assertion fails:
Assert.AreEqual("First", elements[0].Description);
为什么.NET重新安排我的列表时的元素本质上是一样的吗?我想为它仅列表重新排序,如果比较返回一个非零值
Why is .NET reordering my list when the elements are essentially the same? I'd like for it to only reorder the list if the comparison returns a non-zero value.
从List.Sort()方法从MSDN文档:
From the documentation of the List.Sort() method from MSDN:
此方法使用的Array.Sort,它采用了快速排序算法。此实现执行不稳定排序;也就是说,如果两个元素是相等的,它们的顺序可能不是preserved。与此相反,一个稳定的排序preserves中等于元素的顺序
This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
这里的链接: http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx
基本上,排序执行作为设计和记录
Essentially, the sort is performing as designed and documented.