简体   繁体   English

使用linq按对象的2属性排序对象列表

[英]sorting list of objects by 2 property of that objects using linq

class TeamInfo
{
    public int TeamId { get; set; }
    public int Points { get; set; }
    public int Average { get; set; } 
}

TeamId  : 5,22,11,52,59 
Points  : 3, 8, 8,12,16
Average : 8,-2,-4, 1, 5

I have a list of TeamInfo objects( List<TeamInfo> teamInfoList ) I want to sort this list as follows; 我有一个TeamInfo对象List<TeamInfo> teamInfoListList<TeamInfo> teamInfoList )我想按如下方式对此列表进行排序;

TeamId | Points | Average
  59   |  16    |   5
  52   |  12    |   1
  22   |   8    |  -2
  11   |   8    |  -4
  5    |   3    |  -8

I need to sort first by Points(descending) and then Average(descending) if points are the same. 如果点相同,我需要先按点(降序)排序,然后再按平均值(降序)排序。

I tried this; 我试过这个;

List<int> sortTeams = teamInfoList
            .GroupBy(x => new { x.TeamId , x.Points, x.Average })
            .OrderByDescending(x=>new { x.Key.Points, x.Key.Average })
            .Select(i => i.Key.TeamId).ToList();

I guess i need to implement IComparable but i have no idea how to do it. 我想我需要实现IComparable但我不知道该怎么做。

Use ThenBy: 使用ThenBy:

List<int> sortTeams = teamInfoList
    .OrderByDescending(x => x.Points)
    .ThenByDescending(x => x.Average)
    .Select(i => i.TeamId)
    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM