C#以某种方式向列表元素添加排名

C# Add Ranks to listelements in a certain way

我得到了一份按分数排序的球队列表

Team G, Score:7
Team A, Score:5
Team X, Score:4
Team Y, Score:4
Team T, Score:3
Team K, Score:3
Team P, Score:2
Team L, Score:2
Team E, Score:1
Team R, Score:1
Team O, Score:1
Team Q, Score:1

现在我根据他们的分数对这些团队进行排名。

public static void AddRankByScore(List<TeamExtended> teams)
    {
        if (teams == null) return;
        var rank = 1;

        foreach (var team in teams)
        {
            team.Rank= $"{rank}";
            rank++;
        }
    }

结果是这样的

Team G, Score:7, Rank:1
Team A, Score:5, Rank:2
Team X, Score:4, Rank:3
Team Y, Score:4, Rank:4
Team T, Score:3, Rank:5
Team K, Score:3, Rank:6
Team P, Score:2, Rank:7
Team L, Score:2, Rank:8
Team E, Score:1, Rank:9
Team R, Score:1, Rank:10
Team O, Score:1, Rank:11
Team Q, Score:1, Rank:12

但我希望排名看起来像这样

Team G, Score:7, Rank:1
Team A, Score:5, Rank:2
Team X, Score:4, Rank:3
Team Y, Score:4, Rank:3
Team T, Score:3, Rank:5
Team K, Score:3, Rank:5
Team P, Score:2, Rank:7
Team L, Score:2, Rank:7
Team E, Score:1, Rank:9
Team R, Score:1, Rank:9
Team O, Score:1, Rank:9
Team Q, Score:1, Rank:9

我该怎么做?如果球队得分相同,我必须跳过一些排名。

您可以添加一个检查,看看分数是否等于我们检查的 lastscore。如果是,我们开始计算 equalplacing 变量以增加分数,在 lastscore 更改后,根据同一地点的团队数量。

// Last score that team had.
int lastscore = 0;
// Amount of placings on the same spot.
int equalplacing = 1;
// Current rank.
int rank = 0;

foreach (var team in teams) {
    // Check if current team score is not equal to the last team score.
    if (team.Score != lastscore) {
       rank += equalplacing;
       equalplacing = 1;
    }
    else {
        equalplacing++;
    }
    
    team.Rank = rank;
    lastscore = team.Score;
}

为了确保排名有效,您需要以分数作为排序值,按降序对列表进行排序。您可以使用 Linq 和 .OrderByDescending().

teams = teams.OrderByDescending(o=>o.Score).ToList();

Score 属性 对 Team 对象进行分组和排序,按每个组的计数而不是 1 递增排名计数器以获得所需的输出。

LINQ 示例:

public static void AddRankByScore(List<TeamExtended> teams) => teams
    .GroupBy(x => x.Score)
    .OrderByDescending(x => x.Key)
    .Aggregate(1, (r, g) =>
    {
        g.Aggregate(0, (_, t) => t.Rank = r);
        r += g.Count();
        return r;
    });

foreach 示例:

public static void AddRankByScore(List<TeamExtended> teams)
{
    var r = 1;

    foreach (var g in teams
        .GroupBy(x => x.Score)
        .OrderByDescending(x => x.Key))
    {
        foreach (var t in g)
            t.Rank = r;

        r += g.Count();
    }
}

其中每个修改给定列表 (teams) 的 Rank 属性,如下所示:

G, 7, 1
A, 5, 2
X, 4, 3
Y, 4, 3
T, 3, 5
K, 3, 5
P, 2, 7
L, 2, 7
E, 1, 9
R, 1, 9
O, 1, 9
Q, 1, 9