I am making a game. A players name and score are written into a text file once they finish. The text file is converted into a list. I am trying to sort it by highest score to lowest but since Sort() only sorts in alphabetical order, the values are not going in the right places. I want it to be sorted by its value instead.
public partial class frmLeaderboard : Form
{
public frmLeaderboard()
{
InitializeComponent();
CenterToScreen();
WritePlayerTextFile();
GetPlayerHighScore();
}
private void frmLeaderboard_Load(object sender, EventArgs e)
{
}
private void WritePlayerTextFile()
{
FileStream fs;
if (File.Exists("playerscore.txt"))
{
fs = new FileStream("playerscore.txt", FileMode.Append);
}
else
{
fs = new FileStream("playerscore.txt", FileMode.Create);
}
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(frmRegistration.GetPlayer().GetScore() + "," + frmRegistration.GetPlayer().GetUserName());
sw.Close();
fs.Close();
}
private void GetPlayerHighScore()
{
List<string> users = File.ReadLines("playerscore.txt").ToList();
List<string> formattedUsers = new List<string>();
users.Sort();
users.Reverse();
for (int i = 0; i < users.Count; i++)
{
string[] userNameScore = users[i].Split(',');
formattedUsers.Add((i + 1) + ": " + userNameScore[1] + " Score: " + userNameScore[0]);
}
lstLeaderboard.DataSource = formattedUsers;
}
I have tried OrderBy() but i am not familiar with it so i had no luck with it
>Solution :
You were on the right track for OrderBy().
lstLeaderboard.OrderBy(x => x);
And that should sort it Alphabetically. But as this is a leaderboard you would probably want to order it by the user score. The easiest way to do that is first to convert your string into an object;
List<string> users = File.ReadLines("playerscore.txt").ToList();
var userObjects = users.Select(user => new { Name = user.Split(',')[1], Score = user.Split(',')[0]});
var formattedUsers = userObjects.OrderBy(user => user.Score)
.Select((user, index) => $"{index}: {user.Name} Score: {user.Score}")
.ToList();
lstLeaderboard.DataSource = formattedUsers;