gpt4 book ai didi

C# List<> 按 x 然后 y 排序

转载 作者:IT王子 更新时间:2023-10-29 03:37:47 26 4
gpt4 key购买 nike

类似于List<> OrderBy Alphabetical Order ,我们想按一个元素排序,然后按另一个元素排序。我们想要实现等价于

的功能
SELECT * from Table ORDER BY x, y  

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

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

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

最佳答案

对于可以使用 LINQ OrderByThenBy 的 .Net 版本(或 ThenByDescending 如果需要):

using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();

注意:对于 .Net 2.0(或者如果您不能使用 LINQ)请参阅 Hans Passant answer对于这个问题。

关于C# List<> 按 x 然后 y 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/289010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com