C#列表&LT;&GT;排序由X,则y [英] C# List<> Sort by x then y
问题描述
类似名单,其中;&GT;排序依据按字母顺序排列,我们想通过一个元素,然后又进行排序。我们要实现的功能上等同
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 );
}
和我们在列表如下:
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
稳定的排序将preferable,但不是必需的。解决方案,适用于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解决方案仍然是preferable在流行的3.5 LINQ的解决方案,它执行就地分类和不具备LINQ的方法的O(n)的存储需求。除非你preFER原来的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!