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

时间:2013-02-24 19:58:05

标签: c# list sorting

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

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

无序文本文件:

50:James
23:Jessica
70:Ricky
70:Dodger
50:Eric

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

订购清单:

70:Dodger
70:Ricky
50:Eric
50:James
23:Jessica

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

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;

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

5 个答案:

答案 0 :(得分: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();

修改:这是一个包含Ideone数据的演示:http://ideone.com/gtRYO7

答案 1 :(得分:3)

您可以使用ReadAllLines方法轻松读取文件,然后使用OrderByDescending对从您解析的值中的字符串进行排序:

string[] sortedScoreLines =
  File.ReadAllLines(resourcePath + "\\scoreboard.txt")
  .OrderByDescending(s => Int32.Parse(s.Substring(0, s.IndexOf(':'))))
  .ThenBy(s => s)
  .ToArray();

答案 2 :(得分:1)

基于Guffa的回答以及更多评论

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();

答案 3 :(得分:0)

检查一下:

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();
    }

答案 4 :(得分:0)

很多好的答案。我只想提供一个更短的版本:

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

(当然,这是假设您的项目中除了开头没有其他数字)

相关问题