Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Sort(by length) returns different results on different computers

Tags:

c#

sorting

I have the following code :

List<string> Words = item.Split(' ').ToList<string>();
Words.Sort((a, b) => b.Length.CompareTo(a.Length));

Which is supposed to sort a List of words from a line in a file (item) according to their size. However, if two words have the same length, they are supposed to be sorted by the order of appearence in the line.

The problem here is that if the line is, for example "a b c", on my computer, the list will have three sorted items (0 - a, 1 - b, 2 - c), but on another computer, using the same .Net version (4.5), the sorted items will be (0 - c, 1 - b, 2 - a)

Is there a way to enforce the same result troughout different computers ?

like image 649
adre76 Avatar asked Dec 01 '22 15:12

adre76


2 Answers

List.Sort is an unstable sort, meaning in your case that elements of the same length can go in different order.

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.

like image 118
AlexD Avatar answered Dec 22 '22 23:12

AlexD


You can force the same results using LINQ and set of OrderBy/ThenBy calls, instead of Sort.

var result = source.Select((v, i) => new { v, i })
                   .OrderBy(x => x.v.Length)
                   .ThenBy(x => x.i)
                   .Select(x => x.v)
                   .ToList();

But you should be aware, that it will create new list, instead of sorting existing one in place:

like image 29
MarcinJuraszek Avatar answered Dec 22 '22 21:12

MarcinJuraszek