我需要按积分,然后按职位排序。如何通过职位列表属性订购我的列表?
public class Sailor
{
public string Name { get; set; }
public int Points { get; set; }
public List<int> Positions { get; set; }
public Sailor(string name, int points, List<int> positions)
{
Name = name;
Points = points;
Positions = positions;
}
}
var sailors = new List<Sailor>
{
new Sailor("Carl", 20, new List<int> { 2, 2, 4, 1, 1 }),
new Sailor("Paul", 10, new List<int> { 4, 5, 3, 2, 5 }),
new Sailor("Anna", 20, new List<int> { 1, 1, 1, 3, 4 }),
new Sailor("Lisa", 11, new List<int> { 3, 4, 5, 5, 2 }),
new Sailor("Otto", 11, new List<int> { 5, 3, 2, 4, 3 })
};
foreach (var sailor in sailors)
{
sailor.Positions.Sort();
}
var orderedListOfSailors = sailors.OrderByDescending(x => x.Points);
这给了我:
Carl, Anna, Lisa, Otto, Paul
我想要的是:
Anna, Carl, Otto, Lisa, Paul
为什么呢?因为安娜有3个第一名,卡尔有2个。奥托有2个,3个,3个,丽莎有2个,3个,4个。
答案 0 :(得分:0)
问题可以通过对Sailor
的实例使用词典编纂来解决;您可以为Sailor
实施自定义比较器,也可以使用ThenBy
扩展方法。
答案 1 :(得分:0)
按Points
订购后,再次按地点数量排序。
var orderedListOfSailors = sailors
.OrderByDescending(x => x.Points)
.ThenByDescending(x => x.Positions.Count(y => y == 1))
.ThenByDescending(x => x.Positions.Count(y => y == 2))
.ThenByDescending(x => x.Positions.Count(y => y == 3))
.ThenByDescending(x => x.Positions.Count(y => y == 4));