'need help listing a top 5 hangman c#

I am coding hangman game where in every guess the user gets a point. I'm trying to list a top 5 players of the game each time restart button is clicked. For example if highscore was 2 and player reach 3 his name should be shown in a label. I'm taking the name for a player from login/signup form and I need it to be sorted in a txt file .

public static void New_Score(int score, string name)
{
    List<string> scoreList;
    if (File.Exists("scores")) 
        scoreList = File.ReadAllLines("scores").ToList();
    else
        scoreList = new List<string>();
    scoreList.Add(name + " " + score.ToString());
    var sortedScoreList = scoreList.OrderByDescending(ss => int.Parse(ss.Substring(ss.LastIndexOf(" ") + 1)));
    File.WriteAllLines("scores", sortedScoreList.ToArray());
}

// its in a method class calling it in form4 ( Methods.New_Score(User.score, Methods.displayName); then when he click restart :

 List<string> scoreList = File.ReadAllLines("scores").ToList();
    label8.Text = string.Join("\n", scoreList);

Output I am getting:

  1. sam 3

  2. ram 2

  3. jad7

How I want output to be:

  1. jad 7

  2. sam 3

  3. ram 2

So then I can show it in a label like that pls any help would be appreciated.



Solution 1:[1]

maybe missing 'space' in jad7 is a problem: jad 7, since You're searching the score by looking for the last 'space' in the string, try to look at the very last symbol instead.

Or use dedicated class:

using System.Text.Json;

var list = new List<Player>
{
    new Player() {Name = "P1", Score = 1},
    new Player() {Name = "P2", Score = 7},
    new Player() { Name = "P3", Score = 2 }
};

WriteFile.Write(list);
var savedList = ReadFile.Read();

foreach(var p in savedList.OrderByDescending(x=>x.Score))
    Console.WriteLine(p.ToString());

public static class WriteFile
{
    public static void Write(IEnumerable<Player> players)
    {
        var json = JsonSerializer.Serialize(players);
        File.WriteAllText("scores.txt",json);
        
    }
}

public static class ReadFile
{
    public static IEnumerable<Player> Read()
    {
        var json = File.ReadAllText("scores.txt");
        return JsonSerializer.Deserialize<IEnumerable<Player>>(json);
    }
}

[Serializable]
public class Player
{
    public string Name { get; set; }
    public int Score { get; set; }

    public override string ToString()
    {
        return $"{Name} {Score}";
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1