Home > Back-end >  Get the rank based on the score in C#
Get the rank based on the score in C#

Time:02-18

I have a leaderboard page that displays users, scores, and Ranking. I am trying to display the rank based on the user score that is sorted. I have tried a solution I found online, the sort is working fine however the ranking is showing 0 for all users.

public class Leaderboard 
{
    public string Name { get; set; }
    public int Score { get; set; }
    public int Rank { get; set; }
}

private async Task GetContacts()
{
    FireBaseHelper firebaseHelper = new FireBaseHelper();
    Leaderboard = await firebaseHelper.GetUsers();

    Leaderboard.OrderByDescending(item => item.Score).Select((item, i) => new
    {
       item = i,
       Rank = i   1
    });
}

I don't know what I am doing wrong. any idea on how I can fix it?

CodePudding user response:

I think perhaps the problem is you are mixing up which object the Rank is on. You might be misunderstanding what Select((item, i) => new { ... }) does. It creates a new object for every item in the collection. It doesn't update the items in the collection.

I think what you want to do is use a foreach-loop:

private async Task GetContacts()
{
    FireBaseHelper firebaseHelper = new FireBaseHelper();
    Leaderboard = await firebaseHelper.GetUsers();

    var nextRank = 1;
    foreach (var user in Leaderboard.OrderByDescending(item => item.Score))
    {
        user.Rank = nextRank  ;
    }
}

And if you want to take @derpirscher's comment into consideration... if you want two users with the same score to have the same rank:

private async Task GetContacts()
{
    FireBaseHelper firebaseHelper = new FireBaseHelper();
    Leaderboard = await firebaseHelper.GetUsers();

    var nextRank = 1;
    var orderedGroupedUsers = Leaderboard.GroupBy(item => item.Score)
        .OrderByDescending(group => group.Key);
    foreach (var group in orderedGroupedUsers)
    {
        foreach (var user in group)
        {
            user.Rank = nextRank;
        }
        nextRank  ;
    }
}

CodePudding user response:

as Xerillio said, you can not sort string with OrderByDescending change score property type to int if it is possible.

  • Related