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 ?
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.
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:
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