C#对包含数字的字符串列表进行排序

And*_*dré 3 c# sorting list

我正在创建一个读/写文本文件的分数系统.我当前的格式读取文件的每一行并将每行存储到一行中List<string>.一条典型的线就像是50:James (50 being the score, James being the username).

我需要按照分数对列表进行排序,同时保持名称与字符串.这是我的意思的一个例子:

无序文本文件:

50:James
23:Jessica
70:Ricky
70:Dodger
50:Eric
Run Code Online (Sandbox Code Playgroud)

(请注意,有些分数是相同的,阻碍了我使用数字键创建列表的使用)

订购清单:

70:Dodger
70:Ricky
50:Eric
50:James
23:Jessica
Run Code Online (Sandbox Code Playgroud)

我当前的代码(不能与两个或多个相同的分数一起使用)

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;
Run Code Online (Sandbox Code Playgroud)

是的,我知道这是非常低效和丑陋的,但我花了很多时间尝试这么多不同的方法.

Tim*_*ter 10

你可以使用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();
Run Code Online (Sandbox Code Playgroud)

编辑:这是一个关于Ideone数据的演示:http://ideone.com/gtRYO7