c# - .NET 列表排序在所有返回 0 后返回不同的顺序

标签 c# .net list sorting

进入此的初始列表以不同的顺序出现,即使在应用返回 0 时也是如此。我认为返回 0 会使游戏保持与最初处理时相同的顺序,但事实并非如此。如果其他返回都没有命中,顺序不应该与原始数组保持一致吗?

games.Sort((game1, game2) =>
            {
                DateTime? minMaxDate1 = null;
                DateTime? minMaxDate2 = null;

                minMaxDate1 = FindDateRestriction(autoSchedulerLists, game1.AwayTeam, minMaxDate1);
                minMaxDate1 = FindDateRestriction(autoSchedulerLists, game1.HomeTeam, minMaxDate1);

                minMaxDate2 = FindDateRestriction(autoSchedulerLists, game2.AwayTeam, minMaxDate2);
                minMaxDate2 = FindDateRestriction(autoSchedulerLists, game2.HomeTeam, minMaxDate2);

                if (minMaxDate1.HasValue && !minMaxDate2.HasValue)
                    return -1;

                if (minMaxDate2.HasValue && !minMaxDate1.HasValue)
                    return -1;

                if (minMaxDate1.HasValue && minMaxDate2.HasValue && minMaxDate1 != minMaxDate2)
                {
                    return minMaxDate1 < minMaxDate2 ? -1 : 1;
                }

                return 0;
            });

最佳答案

shouldnt the order stay the same as the origional array if all items return 0?

不, List<T>.Sort ...

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

如果你想要一个稳定的排序,你可以使用 LINQ 的 OrderBy .

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key.

所以像这样:

games = games.OrderBy(g => /* logic here */)
             .ToList();

关于c# - .NET 列表排序在所有返回 0 后返回不同的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50570279/

相关文章:

c# - 帮助对 C# 中的文本字符串进行正则表达式验证

c# - 手机浏览器和电脑浏览器的区别

python - 对不同长度的列表求和

Python pandas数据帧从_records读取, "AssertionError: 1 columns passed, passed data had 22 columns"

c# - 我需要 c# 中的一些东西,它像 c++ 中的 setw() 一样工作

c# - 使用 C# 将 double 转换为字符串从 Excel 读取值

c# - 按日期降序对包含日期的字符串数组进行排序

.net - Docker容器未运行Windows系统调用错误

c# - 具有自动实现属性和构造函数初始值设定项的结构

Python:匹配列表中的元素