1. Origin:
KV 7.0 added to the list management function, when dealing with sorting problems, when sorting an empty list by size, date, and length, the order changes, which makes it confusing.
No justice, no! List.sort () method, why is it?
To understand this problem in depth, we find interesting questions: stable and unstable sorting.
2. Stable sort and unstable sort
Find this section on the official Microsoft website:
Remarks
If comparison is provided, the elements of the list<t> be sorted using the method represented by the Deleg Ate.
If comparison is null, an ArgumentNullException is thrown.
This method uses Array.Sort, which applies the introspective Sort as follows:
If the partition size is fewer than-elements, it uses an insertion sort algorithm
If the number of partitions exceeds 2 * Logn, where N is the range of the input array, it uses a heapsort algorithm.
Otherwise, it uses a Quicksort algorithm.
This implementation performs an unstable sort; That is, if the elements is equal, the their order might not be preserved. In contrast, a stable sort preserves the order of elements that is equal.
On average, the This method is a O (n log n) operation, where n is Count; In the worst case it's an O (n ^ 2) operation.
The effect is that this implementation will perform an unstable sort. That is, if two elements are equal, their order may not be preserved.
We build a demo to verify that the use cases are as follows:
varList =Newlist<string>(); List. AddRange (New string[] {"3","2","1","4" }); List. Sort ((x, y)= { return 0; }); foreach(stringSinchlist) Console.WriteLine (s);
Its output is:
To verify the above results, it is inferred that it is fast reversed using the two-point method, and the latter part is pre-placed.
But eight generations we would rather it entered in the original order 3214, this reasonable, but, but, it shameless changed ...
3. Actual scene
For example, we need to sort the specific objects, with a few corrections on the following Web example:
Static voidMain (string[] args) { varP1 =NewPerson () {Name ="Abby", age = - }; varP4 =NewPerson () {Name ="Jason", age = at }; varP2 =NewPerson () {Name ="Bob", age = at }; varP3 =NewPerson () {Name ="Charlie", age = at }; varP5 =NewPerson () {Name ="Danielle", age = - }; varList =NewList<person>(); List. Add (p1); List. ADD (p2); List. ADD (p3); List. ADD (p4); List. Add (p5); List. Sort (); Console.WriteLine ("Unstable List Sort:"); foreach(Person Pinchlist) Console.WriteLine (P); Console.ReadLine (); } classperson:icomparable { Public stringName {Get;Set; } Public intAge {Get;Set; } Public intCompareTo (Objectobj) { intresult =1; if(obj! =NULL&& obj isPerson ) { varperson =(person) obj; Result= This. Age.compareto (person. age);; } returnresult; } Public Override stringToString () {returnString.Format ("{0}-{1}", This. Name, This. Age); } }
Its output is:
Among the 23-year-olds, the three were not in the order of Jason, Bob, Charlie or even in reverse.
I just want it to be added in the same order, what should I do?
For this issue, some articles were suggested to be sorted in LINQ because it is a solid sort, but we are using the. NET Framework 2.0, which is not supported.
On the StackOverflow, encountered a group of same boat, all suggested read, find available methods, add Index!
4. Solution
and modify the person class, add the SortIndex property as follows and fix its comparison function:
classperson:icomparable { Public stringName {Get;Set; } Public intAge {Get;Set; } Public intSortIndex {Get;Set; }
Public intCompareTo (Objectobj) { intresult =1; if(obj! =NULL&& obj isPerson ) { varperson =(person) obj; Result= This. Age.compareto (person. Age); if(Result = =0) Result= This. Sortindex.compareto (person. SortIndex); } returnresult; } ... }
When initializing, add its index:
varP1 =NewPerson () {Name ="Abby", age = -, SortIndex =0 }; varP4 =NewPerson () {Name ="Jason", age = at, SortIndex =1 }; varP2 =NewPerson () {Name ="Bob", age = at, SortIndex =2 }; varP3 =NewPerson () {Name ="Charlie", age = at, SortIndex =3 }; varP5 =NewPerson () {Name ="Danielle", age = -, SortIndex =4};
Output order:
Keep the initial order to resolve the problem.
Postscript:
did not notice before, this problem found is very interesting, degree Niang not to force, solve the problem or to Google, found in the StackOverflow with the same troubled people, have it can refer to the program.
This scenario, which is typically used to customize data structure comparisons, such as a blank list of KV projects, should retain its original order when comparable items are equal, but it is changed, leading to the search for a solution to the problem.
But the official program fixed, can not change the situation, do a curve to save the nation, plus another index in order to fix, although it seems to take some effort, but can solve the problem, it is a good way to use.
Reference Documentation:
List (T). Sort Method (Comparison (T)) (System.Collections.Generic)
C # Stable sort:c# 411
why does List<t>. Sort Method Reorder equal icomparable<t> elements?
C #: List.sort () for robust sorting (stable sort)