Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sorting a list of strings that contains numbers

Tags:

c#

list

sorting

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.

like image 858
André Avatar asked Feb 24 '13 19:02

André


2 Answers

You can use String.Split:

var ordered = list.Select(s => new { Str = s, Split = s.Split(':') })
            .OrderByDescending(x => int.Parse(x.Split[0]))
            .ThenBy(x => x.Split[1])
            .Select(x => x.Str)
            .ToList();

Edit: Here's a demo with your data on Ideone: http://ideone.com/gtRYO7

like image 147
Tim Schmelter Avatar answered Sep 22 '22 13:09

Tim Schmelter


You can use the ReadAllLines method to easily read the file, then OrderByDescending to sort the strings on values that you parse from them:

string[] sortedScoreLines =
  File.ReadAllLines(resourcePath + "\\scoreboard.txt")
  .OrderByDescending(s => Int32.Parse(s.Substring(0, s.IndexOf(':'))))
  .ThenBy(s => s)
  .ToArray();
like image 41
Guffa Avatar answered Sep 23 '22 13:09

Guffa