C# problem List

image
Output on screen.

aa: 6 gissningar
hhh: 6 gissningar
abc: 8 gissningar
uoduwqe: 8 gissningar
i: 11 gissningar
a: 12 gissningar
aa: 8 gissningar
Output from results.txt file.

Score.cs

C#:
namespace GuessTheNumber
{
    class Score : IComparable<Score>
    {
        public string PlayerName { get; set; }
        public int GuessCount { get; set; }

        public int CompareTo(Score other)
        {
            if (other == null) return 1;
            if (this.GuessCount == other.GuessCount)
              {
                 return this.PlayerName.CompareTo(other.PlayerName);
              }

            return this.GuessCount.CompareTo(other.GuessCount);
        }
    }
}

HandleHighScore.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace GuessTheNumber
{
    class HandleHighScore
    {
        private string filePath = "results.txt";

        public bool SaveOrUpdateHighScore(Score score)
        {
            List<Score> scores = FetchHighScore();

          
            scores.Add(score);


           // scores.Sort();

            return SaveAllScores(scores);
        }

        public bool SaveAllScores(List<Score> scores)
        {
            try
            {
                using (StreamWriter sWriter = new StreamWriter(filePath, false))
                {
                    foreach (var score in scores)
                    {
                        sWriter.WriteLine($"{score.PlayerName}: {score.GuessCount} gissningar");
                    }
                }
                return true;
            }
            catch
            {
                Console.WriteLine("Ett fel inträffade vid sparningen.");
                return false;
            }
        }

        public List<Score> FetchHighScore()
        {
            List<Score> scores = new List<Score>();

            if (File.Exists(filePath))
            {
                using (StreamReader sReader = new StreamReader(filePath))
                {
                    string line;
                    while ((line = sReader.ReadLine()) != null)
                    {
                        string[] data = line.Split(':');
                        if (data.Length == 2 && int.TryParse(data[1].Trim().Split(' ')[0], out int guessCount))
                        {
                            scores.Add(new Score { PlayerName = data[0], GuessCount = guessCount });
                        }
                    }
                }

                scores.Sort();
            }

            return scores;
        }
    }

GuessNumberGame.cs

using System;
using System.Collections.Generic;

namespace GuessTheNumber
{
    class GuessNumberGame
    {
        private bool runGame;
        private HandleHighScore saveScoreList;

        public GuessNumberGame()
        {
            saveScoreList = new HandleHighScore();
        }

        public void PlayGame()
        {
            do
            {
                List<int> guesses = new List<int>();
                Random random = new Random();
                int numberToGuess = random.Next(1, 101);

                Console.WriteLine("Start av nytt spel.");

                while (true)
                {
                    Console.Write("Gissa på ett tal mellan 1 och 100: ");
                    int userGuess;

                    while (!int.TryParse(Console.ReadLine(), out userGuess))
                    {
                        Console.Write("Ogiltigt tecken. ");
                    }

                    guesses.Add(userGuess);

                    if (userGuess == numberToGuess)
                    {
                        Console.WriteLine("Grattis, du gissade rätt nummer.");
                        Console.WriteLine($"Det tog dig {guesses.Count} gissningar.");

                        Console.Write("Ange ditt namn: ");
                        string playerName = Console.ReadLine();

                        Score gameScore = new Score
                        {
                            PlayerName = playerName,
                            GuessCount = guesses.Count
                        };
                        saveScoreList.SaveOrUpdateHighScore(gameScore);

                        List<Score> sortedScores = saveScoreList.FetchHighScore();
                        Console.WriteLine("High Scores:");
                        int test;
            
                        foreach (var score in sortedScores)
                        {
                          
                          {

                            Console.WriteLine($"{score.PlayerName}: {score.GuessCount} gissningar");
                          }
                        }

                        break;
                    }
                    else if (userGuess < numberToGuess)
                    {
                        Console.WriteLine(userGuess + " är för lågt! Försök igen.");
                    }
                    else
                    {
                        Console.WriteLine(userGuess + " är för högt! Prova igen.");
                    }
                }

                Console.Write("Vill du spela igen? (ja/nej): ");
                runGame = WillPlay(Console.ReadLine());

            } while (runGame);

            Console.WriteLine("Thank you for playing!");
        }

        private bool WillPlay(string response)
        {
            return response.Equals("ja", StringComparison.OrdinalIgnoreCase);
        }
    }
}
}

I want only print out the high score from the file. Only the best result from each person on the screen. In other words, no duplicates of names with scores.
Hope you can help me.

The output on screen should look like
aa: 6 gissningar
hhh: 6 gissningar
abc: 8 gissningar
uoduwqe: 8 gissningar
i: 11 gissningar
a: 12 gissningar

My C# syntax is a bit rusty so bare with me, but I can speak to the logic of this.

If you are wanting to only save the highest score for each person, rather than saving all scores, you might consider saving scores in a ‘Dictionary’ rather than a ‘List’. That way you avoid ever saving multiple scores for a given user.
Then when you go to save a score, check first if the (the user that is) already exists in your Dictionary using:

 if (!scores.PlayerName.Contains(score)) 
  {
   scores.Add(score);
  } 
else {
*compare existing GuessCount to this.GuessCount and save the better one*
}

(actually that .Contains() check is likely already built in for Dictionary, but may be useful if you continue to use List.)

If the player does not yet have a score, save the score, else compare to the player’s existing score and save the highest. Since a player only every has one high score, when you go to print using your existing method, you won’t have duplicate results.

If you are wanting to maintain the data of all the scores, but only print each person’s high score you have a bit more work to do. At the surface, you could just use the .Distinct LINQ method

to only get the distinct values. However, since you want the best score for each user, you’d need to select distinct PlayerNames and then select their highest score.

LINQ syntax can be a beast but it can be very powerful for just this sort of thing.