在c#中按字母顺序排序文本文件

时间:2015-01-03 04:40:52

标签: c# sorting text alphabetical-sort

我正在尝试在C#中编写一个程序,该程序对包含familyname的文本文件进行排序,后跟逗号,后跟名字。我如何根据姓氏按字母顺序获取文本文件。

3 个答案:

答案 0 :(得分:5)

根据细节的不同,有很多选择。未经测试,但这样的事情应该很接近。

string inFile = @"C:\someInFile.txt";
string outFile = @"C:\someOutFile.txt";
var contents = File.ReadAllLines(inFile);
Array.Sort(contents);
File.WriteAllLines(outFile, contents)

答案 1 :(得分:0)

这是VB.NET,但翻译应该很简单:

Public Sub FileCreateReadAndSort()
    'Read data from database and write to unsorted text file
    Dim dv As DataView = DataLib.QryToData("select  * from gen where rn<10", EnumLib.DBList.Gen, EnumLib.DataObj.DataView)
    Dim S As String = ""
    For i As Integer = 0 To dv.Count - 1
        With dv(i)
            S = S & RTrim(.Item("surname")) & ", " & RTrim(.Item("name")) & vbCrLf
        End With
    Next
    Dim SW As IO.StreamWriter = New IO.StreamWriter("c:\temp\fileOriginal.txt")
    SW.Write(S)
    SW.Flush()
    SW.Close()
    SW.Dispose()

    'read in unsorted text file
    Dim SR As IO.StreamReader = New IO.StreamReader("c:\temp\fileOriginal.txt")
    Dim S2 As ArrayList = New ArrayList
    Do While Not SR.EndOfStream
        S2.Add(SR.ReadLine)
    Loop

    'sort file lines and write to sorted file
    Dim S3 As Array = S2.ToArray
    Array.Sort(S3)

    Dim SW2 As IO.StreamWriter = New IO.StreamWriter("c:\temp\fileSorted.txt")
    For i As Integer = 0 To S3.Length - 1
        SW2.Write(S3(i) & vbCrLf)
    Next i
    SW2.Flush()
    SW2.Close()
    SW2.Dispose()
End Sub

希望这有帮助!

戴夫

答案 2 :(得分:0)

你可以使用这个,

FileStream readerStream = new FileStream(@"Desktop\Source\text.txt", FileMode.Open);
string[] content = null;

//Read the content
using (StreamReader reader = new StreamReader(readerStream))
{
   content = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

   //Remove the entries in the file
   readerStream.SetLength(0);
}

FileStream writerStream = new FileStream(@"Desktop\Source\text.txt", FileMode.OpenOrCreate);
using (StreamWriter writer = new StreamWriter(writerStream))
{
   //Sort the content and write back to the same file
   Array.Sort(content);
   writer.Write(string.Join(Environment.NewLine, content));
}