按列表属性对列表列表进行排序<int>



我需要按点排序,然后按位置排序。如何通过"职位列表"属性对列表进行排序?

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,4。

该问题可以通过在Sailor的实例上使用字典编码来解决;您可以为Sailor实现一个自定义比较器,也可以使用ThenBy扩展方法。

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));

相关内容

  • 没有找到相关文章

最新更新