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

时间:2018-11-07 18:16:31

标签: c# linq sorting

import request from 'request';

// dataPayCode has 18000 objects [ { id:1, test: 'test' }, ..........]
request.post({url:apiURLGM + 'api/migration/paycode', json: dataPayCode}, function(err,httpResponse,body){
    console.log(body);
});

我有一个TeamInfo对象列表(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 ) 我要对该列表进行如下排序;

List<TeamInfo> teamInfoList

如果点相同,我需要先按Points(降序)排序,然后再按Average(降序)排序。

我尝试过了

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

我想我需要实现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(); ,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:3)

使用然后按:

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