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

I have the following code:

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

which should sort the list of words from a line in a file (element) according to their size. However, if two words have the same length, they must be sorted in the order they appear on the line.

The problem is that if a line, for example, "abc", on my computer, the list will have three sorted elements (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 provide the same result on different computers?

+4
source share
3 answers

, LINQ OrderBy/ThenBy Sort.

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

, , , :

+7

List.Sort , , .

; , , . , .

+10

List.Sort() . .

2 : , , .

- Insertion. , , SortedList, . , Linq, . !

. , . , . , , .

+1

All Articles