DTMG
DTMG

Reputation: 21

Having problems sorting items in a listbox

I am reading a list of high scores for my game from a text file using StreamReader. I am then sorting it using .Sort()

I converted it to an array and passed it into a list box on a form in the game. The score is saved to the text file in a string (score+" - "+username)

public frmHighScores()
    {
        InitializeComponent();

        List<string> scores = new List<string>();
        StreamReader inputFile = File.OpenText("High Scores.txt");
        while (!inputFile.EndOfStream)
        {
            scores.Add(inputFile.ReadLine());
        }
        scores.Sort();
        lstScores.Items.AddRange(scores.ToArray());
    }

As it is a string the Sort method is only sorting the first number in the score and I'm not sure how to rectify it.

Here is the image of the sorted list

I want it to read as follows

200
120
105
65

Upvotes: 2

Views: 78

Answers (2)

mrkg
mrkg

Reputation: 68

You could use a Dictionary to store these values (score and username). This will eable you to order using a real numeric type. You can build this dictionary by splitting the strings, as follows:

public void frmHighScores()
    {
        // Pretend we read this from the file
        List<string> fakeFileValues = new List<string>() { "20 steve", "100 john", "25 jane" };
        Dictionary<int, string> scores = new Dictionary<int, string>();

        foreach (string s in fakeFileValues)
        {
            // Better ways to do this, just expanding for clarity
            string[] split = s.Split(' ');
            scores.Add(int.Parse(split[0]), split[1]);
        }

        // You can then order by a real numeric value
        scores.OrderBy(x => x.Key);
    }

Upvotes: 2

HaukurHaf
HaukurHaf

Reputation: 13796

You could use the LINQ OrderByDescending extension method and pass inn the value which comes before the "-" sign, something like that:

scores = scores.OrderByDescending(x=>Convert.ToInt32(x.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0]).Trim());

Upvotes: 1

Related Questions