为什么名单< T> .Sort方法重新排序等于IComparable的< T>内容是什么? [英] Why does List<T>.Sort method reorder equal IComparable<T> elements?

查看:211
本文介绍了为什么名单< T> .Sort方法重新排序等于IComparable的< T>内容是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多么列表进行排序的方法处理排序的问题。考虑到以​​下因素:

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.

这里的链接: <一href="http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx">http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx

基本上,排序执行作为设计和记录

Essentially, the sort is performing as designed and documented.

这篇关于为什么名单&LT; T&GT; .Sort方法重新排序等于IComparable的&LT; T&GT;内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆