C#对包含数字的字符串列表进行排序 [英] C# Sorting a list of strings that contains numbers

查看:245
本文介绍了C#对包含数字的字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

无序文本文件:

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)

订购清单:

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.

推荐答案

您可以使用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();

编辑:以下是有关您在Ideone上的数据的演示: http://ideone.com/gtRYO7

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

这篇关于C#对包含数字的字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆