如果我想根据多个属性来排序列表,除了将这些属性形成为数字然后使用OrderBy
,我看不出有什么好的方法,例如:
int someArbitraryNumber = 1000;
List<Tuple<int, int>> test = new List<Tuple<int, int>>() {
new Tuple<int, int>(1, 3),
new Tuple<int, int>(1, 4),
new Tuple<int, int>(1, 5),
new Tuple<int, int>(2, 3),
new Tuple<int, int>(9, 15)
};
var orderedTest = test
.OrderBy(x => x.Item1 + x.Item2 * someArbitraryNumber);
在这里,我希望得到的列表是:
(1, 3),
(2, 3),
(1, 4),
(1, 5),
(9, 15)
也就是说,先按第二项排序,再按第一项排序。
使用ThenBy()
:
int someArbitraryNumber = 10000; // Not used anymore
List<Tuple<int, int>> test = new List<Tuple<int, int>>() {
new Tuple<int, int>(1, 3),
new Tuple<int, int>(1, 4),
new Tuple<int, int>(1, 5),
new Tuple<int, int>(2, 3),
new Tuple<int, int>(9, 15)
};
var orderedTest = test.OrderBy(x => x.Item2).ThenBy(x => x.Item1);
var
如果编译器可以找出变量的类型,则使用(int, int)
而不是Tuple<int, int>
),您可以为项目使用名称var test = new List<(int first, int second)>()
{
(1, 3), (1, 4), (1, 5), (2, 3), (9, 15)
};
var orderedTest = test.OrderBy(x => x.second).ThenBy(x => x.first);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句