I'm making a leaderboard for the leveling system my Discord bot has. The list will make a list of the people with most XP and order them from highest to lowest amount. I have already achieved this goal, but I can only show to user's ID next to their XP amount in the leaderboard. How can I turn this user ID into a username?
foreach (ulong n in DbContext.Experiences.OrderByDescending(x =>
x.XP).Select(x => x.ID))
{
Context.Guild.GetUser(n).ToString()
}
var leaderboard = string.Concat(DbContext.Experiences.OrderByDescending(x =>
x.XP).Select(x => $"Level {x.LevelNumber} with {x.XP} xp
{//username must be here}\n"));
await ReplyAsync(leaderboard.ToString());
See comments in code:
//What exactly is this for loop meant to do?
//You appear to be getting a user based on ID and doing nothing with that value.
//This should be removed
foreach (ulong n in DbContext.Experiences.OrderByDescending(x =>
x.XP).Select(x => x.ID))
{
//While this is how to get a user by ID, you aren't actually doing anything with this once it's retrieved.
Context.Guild.GetUser(n).ToString()
}
//You can simply fetch the username here, given that you have access to the ID
var leaderboard = string.Concat(DbContext.Experiences.OrderByDescending(x =>
x.XP).Select(x => $"Level {x.LevelNumber} with {x.XP} xp
{//username must be here}\n"));
await ReplyAsync(leaderboard.ToString());
Your modified code should look something like:
var leaderboard = string.Join("\n", DbContext.Experiences
.OrderByDescending(x => x.XP)
.Select(x => $"Level {x.LevelNumber} with {x.XP} xp {Context.Guild.GetUser(x.ID).ToString()}"));
await ReplyAsync(leaderboard);
NOTE: I've replaced string.Concat
with string.Join
as it's a more efficient String building method.