6

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.

4

5 回答 5

19

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

于 2013-02-24T20:03:33.383 回答
3

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();
于 2013-02-24T20:04:44.813 回答
3

Lots of good answers already. I just wanted to provide an even shorter version:

List<string> ordered = list.OrderByDescending(s => int.Parse(Regex.Match(s, @"\d+").Value)).ToList();

(of course, this assumes that there are no other numbers in your items besides the ones at the beginning)

于 2019-03-18T14:45:07.923 回答
1

Based on Guffa's answer with some more comments

string[] sortedScoreLines =
            File.ReadAllLines(resourcePath + "\\scoreboard.txt");

        // parse into an anonymous class
        var parsedPersons = from s in sortedScoreLines
                            select new
                                       {
                                           Score = int.Parse(s.Split(':')[0]),
                                           Name = s.Split(':')[1]
                                       };

        // sort the list
        var sortedPersons = parsedPersons.OrderByDescending(o => o.Score).ThenBy(i => i.Name);

        // rebuild the resulting array
        var result = (from s in sortedPersons
                     select s.Score + ":" + s.Name).ToArray();
于 2013-02-24T20:18:57.877 回答
0

Check this:

var sortedScoreLines = GetLines("inputFilePath")
        .Select(p => new { num = int.Parse(p.Split(':')[0]), name = p.Split(':')[1] })
        .OrderBy(p => p.num)
        .ThenBy(p => p.name)
        .Select(p => string.Format("{0}:{1}", p.num, p.name))
        .ToList();

    private static List<string> GetLines(string inputFile)
    {
        string filePath = Path.Combine(Directory.GetCurrentDirectory(), inputFile);
        return File.ReadLines(filePath).ToList();
    }
于 2013-02-24T20:11:07.933 回答