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); } }
If I try to sort it this way:
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();
Then the first element is the previously second element "Second". Or, in other words, this assertion fails:
Assert.AreEqual("First", elements[0].Description);
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<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of this method as follows: Sort(IComparer<T>)
Sort isn't stable. However, the LINQ OrderBy methods (and OrderByDescending etc) are stable, which can be very useful.
Since the name is a string , Python by default sorts it using the alphabetical order. For the second case, age ( int ) is returned and is sorted in ascending order. For the third case, the function returns the salary ( int ), and is sorted in the descending order using reverse = True .
In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.
From the documentation of the List.Sort() method from MSDN:
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.
Here's the link: http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx
Essentially, the sort is performing as designed and documented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With