I am creating a score system which reads/writes to a text file. My current format reads each line of the file and stores each line into a List<string>
. A typical line would be something like 50:James (50 being the score, James being the username)
.
I need to order the list by the score while keeping the name with the string. Here's an example of what I mean:
Unordered text file:
50:James
23:Jessica
70:Ricky
70:Dodger
50:Eric
(Notice how there are some scores that are the same, hindering my use of creating a list using numerical keys)
Ordered List:
70:Dodger
70:Ricky
50:Eric
50:James
23:Jessica
My current code (That does NOT work with two or more of the same score)
Dictionary<int, string> scoreLines = new Dictionary<int, string>();
if (!File.Exists(scorePath))
{
File.WriteAllText(scorePath, "No Scores", System.Text.Encoding.ASCII);
}
StreamReader streamReader = new StreamReader(resourcePath + "\\scoreboard.txt");
int failedLines = 0;
while (failedLines < 3)
{
string line = streamReader.ReadLine();
if (String.IsNullOrEmpty(line))
{
failedLines++;
continue;
}
scoreLines.Add(int.Parse(line.Split(':')[0]), line.Split(':')[1]);
}
var arr = scoreLines.Keys.ToArray();
arr = (from a in arr orderby a descending select a).ToArray();
List<string> sortedScoreLines = new List<string>();
foreach (int keyNum in arr)
{
sortedScoreLines.Add(keyNum + ":" + scoreLines[keyNum]);
}
return sortedScoreLines;
Yes, I know this is TERRIBLY inefficient and ugly, but I spent ages trying so many different methods.