Search code examples
c#textstreamwriter

Sort lines in a text file by value


I would like to like the WPF application saves time similar to the one in the rankings. Time and number of attempts is not a problem to list but the problem occurs when I want to sort it in a text file. The user will be able to turn on the leaderboard in a text file as well as when the application is completed, the chart (text file) will open and show the user's time.

 private void writeText(string strPath, TimeSpan tsDuration)
    {
        using (StreamWriter str = new StreamWriter(strPath, true))
        {
            str.WriteLine(tsDuration / suma);
            //duration= time of the game
          //suma= number of attempts
        }
    }
readonly string path = @"C:\Users\info\Desktop\žebříček.txt";
TimeSpan duration = TimeSpan.FromMilliseconds(mt.ElapsedMilliseconds);//this is from other methods

The picture is seen as it is stored now: this is how it is stored now

But I would like it to be stored like this, and the other attempts were sorted by the value of time: future text file

Each time the application is completed, the user's new time should be sorted by how fast it was. I will be happy for any advice

Thank you


Solution

  • I'm sure there are much smarter ways of achieving the same result but a very simple way would be to:

    • Read the contents of the file
    • Assign the contents to a list
    • Append your value to the list
    • Use linq to order the list accordingly
    • Write the list back to the file

    Example:

    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    private void WriteText(string strPath, TimeSpan tsDuration)
    {
        //Create new list of type 'TimeSpan'
        var list = new List<TimeSpan>();
    
        //Read the contents of the file and assign to list
        string line;
        using (var sr = new StreamReader(strPath))
        {
            while ((line = sr.ReadLine()) != null)
            {
                list.Add(TimeSpan.Parse(line));
            }
        }
    
        //Add your time value to the list
        list.Add(tsDuration);
    
        //Order the list in descending order - use OrderBy for ascending
        list.OrderByDescending(i => i);
    
        //Write contents back to file - note: append = false
        using StreamWriter str = new StreamWriter(strPath, false);
        foreach (var item in list)
        {
            str.WriteLine(item);
        }
    }
    
    readonly string path = @"C:\Users\info\Desktop\žebříček.txt";
    TimeSpan duration = TimeSpan.FromMilliseconds(mt.ElapsedMilliseconds);//this is from other methods