C#列表<>按 x 然后 y 排序

编程入门 行业动态 更新时间:2024-10-13 08:21:02
本文介绍了C#列表<>按 x 然后 y 排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

类似于列表OrderBy Alphabetical Order,我们想先按一个元素排序,然后再按另一个元素排序.我们想要实现与

Similar to List<> OrderBy Alphabetical Order, we want to sort by one element, then another. we want to achieve the functional equivalent of

SELECT * from Table ORDER BY x, y

我们有一个包含许多排序函数的类,我们没有问题按一个元素排序.例如:

We have a class that contains a number of sorting functions, and we have no issues sorting by one element. For example:

public class MyClass { public int x; public int y; } List<MyClass> MyList; public void SortList() { MyList.Sort( MySortingFunction ); }

我们在列表中有以下内容:

And we have the following in the list:

Unsorted Sorted(x) Desired --------- --------- --------- ID x y ID x y ID x y [0] 0 1 [2] 0 2 [0] 0 1 [1] 1 1 [0] 0 1 [2] 0 2 [2] 0 2 [1] 1 1 [1] 1 1 [3] 1 2 [3] 1 2 [3] 1 2

稳定排序更可取,但不是必需的.欢迎适用于 .Net 2.0 的解决方案.

Stable sort would be preferable, but not required. Solution that works for .Net 2.0 is welcome.

推荐答案

请记住,如果比较所有成员,则不需要稳定排序.根据要求,2.0 解决方案可能如下所示:

Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:

public void SortList() { MyList.Sort(delegate(MyClass a, MyClass b) { int xdiff = a.x.CompareTo(b.x); if (xdiff != 0) return xdiff; else return a.y.CompareTo(b.y); }); }

请注意,这个 2.0 解决方案仍然优于流行的 3.5 Linq 解决方案,它执行就地排序并且没有 Linq 方法的 O(n) 存储要求.除非您当然更喜欢原封不动的 List 对象.

Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.

更多推荐

C#列表&lt;&gt;按 x 然后 y 排序

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

发布评论

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

>www.elefans.com

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