读取文件并按特定规则按字母顺序对其进行排序

时间:2014-04-13 00:56:33

标签: c# sorting streamreader streamwriter

我需要从文本文件nameInput.txt中读取名称列表,名称格式为first_name,last_name,每行一对。

例如:

David,Smith
Russell,Jones
Andrew,Jones

然后我需要按字母顺序排列,使用主键姓,辅助键名,例如:

Jones Andrew
Jones Russell
Smith David 

最后,我需要将已排序的数据写入另一个文件nameOutput.txt,这些名称按last_name first_name顺序每行写成一对,例如:

Jones Andrew
Jones Russell
Smith David

这是我目前的代码:

    class MainClass
{
    public static void Main (string[] args)
    {

        List<string> list = new List<string> ();
        using (StreamReader reader = new StreamReader("Documents/inputName.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null) 
            {
                list.Add (line);
                Console.WriteLine (line);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果您被允许使用LINQ方法,请参阅以下示例:

 var lines = File.ReadLines("inputFilePath")
            .Select(x => x.Split(',').Reverse().ToArray())
            .OrderBy(x => x[0])
            .ThenBy(x => x[1])
            .Select(x => string.Join(" ", x));

File.WriteAllLines("outputFilePath", lines);

更新:以下是您的代码的非linq解决方案:

创建自定义比较器:

public class NameComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x == null && y == null) return 0;

        if (x == null || y == null) return -1; 

        var parts1 = x.Split();
        var parts2 = y.Split();

        if (parts1.Length > 1 && parts2.Length > 1)
        {
            if (parts1[0] != parts2[0]) return parts1[0].CompareTo(parts2[0]);

            return parts1[1].CompareTo(parts2[1]);
        }

        return x.CompareTo(y);
    }
}

并使用它来对你的名字进行排序:

List<string> list = new List<string>();
using (StreamReader reader = new StreamReader("Documents/inputName.txt"))
{
      string line;
      while ((line = reader.ReadLine()) != null)
      {
           var parts = line.Split(',');
           Array.Reverse(parts);
           list.Add(string.Join(" ", parts));
      }
}

list.Sort(new NameComparer());
using (StreamWriter writer = new StreamWriter("outputfile.txt"))
{
    foreach(var line in list)
         writer.WriteLine(line);
}