I got a list with teams sorted by their score
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
Now I am ranking these Teams by their score.
public static void AddRankByScore(List<TeamExtended> teams)
{
if (teams == null) return;
var rank = 1;
foreach (var team in teams)
{
team.Rank= $"{rank}";
rank++;
}
}
The result looks like this
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
But I want the ranks to look like this
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
How do I do that? I have to skip some ranks if teams have the same score.
You can just add a check that sees if the score is equal to the lastscore
we checked. If it is we start counting up our equalplacing
variable to increase the score, after lastscore
changed, according to the amount of teams on the same spot.
// 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;
}
To make sure the ranking works you need to sort the list in desceding order with the score as the sort value. You can do that with Linq and .OrderByDescending()
.
teams = teams.OrderByDescending(o=>o.Score).ToList();