Sorting an array that has numbers and text

The issue is that you're storing and sorting the numbers as strings. The string "1000" is considered 'less than' the string "200", which is why you're seeing that score entry pop up where it does. You want to be sorting the scores as integers to get the proper order. There's a few ways to do this, but one approach would be to create a class with a string Name property and an int Score property (Warning: I haven't tested any of the code below) public ScoreRecord { public string Name { get; set; } public int Score { get; set; } }

In your program, you would store an array of ScoreRecord objects. When you read the file, you could populate it like this: string[] highScoreStrings = File.ReadAllLines("highscores.txt"); ScoreRecord[] highScores = new ScoreRecord[highScores.Length]; for (int i = 0; i < highScores.Length; i++) { ScoreRecord record = new ScoreRecord(); string[] pieces = highScoreStrings[i].Split(','); record.Name = pieces[0].Trim(); record.Score = int.Parse(pieces[1].Trim()); }

Then, when you want to sort the scores, you could do: IEnumerable<ScoreRecord> sorted = highScores.OrderBy(s => s.Score).Reverse();

And to print them, you could do something like: File.WriteAllLines(sorted.Select(s => string.Format("{0},{1}", s.Name, s.Score)));

To go a step further, I would probably just use the XmlSerializer class to handle all the file formatting and parsing. https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx

There are other approaches you could take too, this was just the first to pop into my head.

/r/csharp Thread