Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

C# List.Sort gives different ouput for the same code in different projects

I have the following code, which produces different outputs depending on the project I run it from. All project properties look the same and it's both using the same lib.

List<(string, int)> numbers = new List<(string, int)>() { ("ID", 0), ("AL", 0), ("D2", 50), ("D3", 50), ("D4", 50) };

        int counter = 0;

        numbers.Sort(delegate ((string, int) item1, (string, int) item2)
        {
            int change = item1.Item2.CompareTo(item2.Item2);

            counter++;

            return change;
        });

        string ans2 = String.Join(" ", numbers.Select(item => item));

The sort method is from System.Collections.Generic. #region Assembly mscorlib, Version=4.0.0.0, Culture=neutral

.Net Framework 4.7.2 Project1:

The final result is "(AL, 0) (ID, 0) (D4, 50) (D3, 50) (D2, 50)" The counter is 20.

.Net Framework 4.7.2 Project2:

The counter is 4.

The final result is "(ID, 0) (AL, 0) (D2, 50) (D3, 50) (D4, 50)"

Can anyone help me understand why the different iteration counts and outputs are different?

I understand the List.Sort() performs an unstable sort, which means that if two elements are equal their order might not be preserved. But it still does not explain the iteration difference.

question from:https://stackoverflow.com/questions/65939866/c-sharp-list-sort-gives-different-ouput-for-the-same-code-in-different-projects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...