如何使用字符串和整数对文本文件进行排序

时间:2019-12-18 12:06:27

标签: c# bubble-sort insertion-sort

我最近一直在尝试编写将文本文件排序到文本框(如排行榜)的代码。我一直在尝试按高分或按字母顺序排序

this is how the text file is saved

如何使用插入或冒泡排序对这些消息进行排序?

2 个答案:

答案 0 :(得分:2)

如果要排序,则必须将数据分解为一个对象,该对象将各个部分保留在单独的属性中。然后,为对象的种类编写一个比较器,然后应用该比较器。

具有Comparer类的示例:

public static class Program
{
    public static void Main()
    {
        var rawData = @"Guest 450
Ryan 300
Ryan 4850
Ryan 100
Guest 300
Guest 1800";

        var players = rawData
            .Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
            .Select(row => row.Split())
            .Select(elements => new Player { Name = elements[0], Score = int.Parse(elements[1]) })
            .ToList();

        players.Sort(PlayerComparer.Default);

        foreach (var player in players)
        {
            Console.WriteLine(player);
        }
    }
}

public class PlayerComparer : IComparer<Player>
{
    public static readonly IComparer<Player> Default = new PlayerComparer();

    public int Compare(Player x, Player y)
    {
        if (x == null)
            return -1;

        if (y == null)
            return 1;

        var scoreComparison = y.Score - x.Score;

        if (scoreComparison != 0)
            return scoreComparison;

        return StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
    }
}

public class Player
{
    public string Name { get; set; }
    public int Score { get; set; }
    public override string ToString() => $"{Name} {Score}";
}

根据您的需求,您还可以将比较器类的用法替换为LINQ查询:

public static class Program
{
    public static void Main()
    {
        var rawData = @"Guest 450
Ryan 300
Ryan 4850
Ryan 100
Guest 300
Guest 1800";

        var players = rawData
            .Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
            .Select(row => row.Split())
            .Select(elements => new Player { Name = elements[0], Score = int.Parse(elements[1]) })
            .ToList();

        var sortedPlayers = players
            .OrderByDescending(player => player.Score)
            .ThenBy(player => player.Name);

        foreach (var player in sortedPlayers)
        {
            Console.WriteLine(player);
        }
    }
}

答案 1 :(得分:0)

您可以简单地执行以下操作:

string path = "C:\\Users\\file\\Desktop\\test.txt";
string delim = ' ';

  string[] lines = File.ReadAllLines(path);
  List<Tuple<string, int>> users = new List<Tuple<string, int>>();

  foreach (string line in lines)
  {
    string[] keyValue = line.Split(delim);

    users.Add(new Tuple<string, int>(keyValue[0], int.Parse(keyValue[1])));
  }

  // sort by users
  users.Sort((x, y) => y.Item1.CompareTo(x.Item1));

  // sort by scores
  users.Sort((x, y) => y.Item2.CompareTo(x.Item2));

省略了对int.Parse和line.Split的错误处理。

方法2:

  string path = "C:\\Users\\user\\Desktop\\test.txt";

  // sorted scores
  var sortedPlayersByScores = File.ReadAllLines(path)
                                  .Select(line => line.Split(' '))
                                  .Select(elem => new 
                                   Tuple<string, int>(elem[0], int.Parse(elem[1])))
                                  .OrderBy(x => x.Item2);

  // sorted players by name
  var sortedPlayersByName = File.ReadAllLines(path)
                                .Select(line => line.Split(' '))
                                .Select(elem => new 
                                 Tuple<string, int>(elem[0], int.Parse(elem[1])))
                                .OrderBy(x => x.Item1);