为什么我的List.Sort方法在C#中颠倒了我的列表的顺序?(Why is my List.Sort method in C# reversing the order of my list?)

编程入门 行业动态 更新时间:2024-10-24 22:21:54
为什么我的List.Sort方法在C#中颠倒了我的列表的顺序?(Why is my List.Sort method in C# reversing the order of my list?)

我有一个通用列表中的项目列表:

A1(排序索引1) A2(分类索引2) B1(分类索引3) B2(分类索引3) B3(分类索引3)

它们上的比较器的形式如下:

this.sortIndex.CompareTo(other.sortIndex)

当我在项目列表上做一个List.Sort()时,我得到以下命令:

A1 A2 B3 B2 B1

很显然,排序索引的顺序是正确的,但我真的不希望它重新排序'B'项。

我可以对比较器做任何调整以解决这个问题吗?

I have a list of items in a generic list:

A1 (sort index 1) A2 (sort index 2) B1 (sort index 3) B2 (sort index 3) B3 (sort index 3)

The comparator on them takes the form:

this.sortIndex.CompareTo(other.sortIndex)

When I do a List.Sort() on the list of items, I get the following order out:

A1 A2 B3 B2 B1

It has obviously worked in the sense that the sort indexes are in the right order, but I really don't want it to be re-ordering the 'B' items.

Is there any tweak I can make to my comparator to fix this?

最满意答案

OrderBy保留相同商品的订单:

myList = myList.OrderBy(item => item.SortIndex).ToList();

OrderBy preserves order for equal items:

myList = myList.OrderBy(item => item.SortIndex).ToList();

更多推荐

本文发布于:2023-08-07 21:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   方法   列表   Sort   List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!