我有一个清单:
List<Tuple<int, int>> MyList = new List<Tuple<int, int>>();
Run Code Online (Sandbox Code Playgroud)
列表的值如下:
int int
0 2
0 1
0 4
1 2
1 3
1 0
2 0
2 9
2 1
3 2
3 5
3 2
Run Code Online (Sandbox Code Playgroud)
如何list按的最高值排序Item2但保存的顺序Item1?如下所示:
int int
2 0
2 9*
2 1
3 2
3 5*
3 2
0 2
0 1
0 4*
1 2
1 3*
1 0
Run Code Online (Sandbox Code Playgroud)
尝试使用MyList.OrderBy(x => x.Item2)但没有成功
如我所见,您要订购组(不是单个项目):
group with Item1 == 2优先,因为该组在所有其他组中的最大值Item2(9);组与Item1 == 1是最后,其最大Item2的值(3)是其它基团中的最小
2 0
2 9*
2 1
...
1 2
1 3*
1 0
Run Code Online (Sandbox Code Playgroud)
要订购组,请尝试GroupBy:
var result = MyList
.GroupBy(item => item.Item1) // groups
.OrderByDescending(group => group.Max(item => item.Item2)) // are ordered
.SelectMany(group => group); // then expanded
Run Code Online (Sandbox Code Playgroud)