我正在读记事本。 当我在visual basic中使用sort函数对它们进行排序时,我注意到结果不准确。
For example
hello i am who 1
I am who hello 14
am hello who I 13
我需要排序第五列,任何想法如何在visual basic中做到这一点?
答案 0 :(得分:0)
您可以通过将文本文件中的数据解析为元组列表,然后使用orderby按第五列排序来实现此目的,例如:
Module Module1
Sub Main()
'I put this dialog here so you can browse to wherever your text file is
Dim SelectFileDialog As New OpenFileDialog
Dim Result As DialogResult = SelectFileDialog.ShowDialog()
If(Result <> DialogResult.OK)
Exit Sub
End If
Dim FilePath As String = SelectFileDialog.FileName
'read all the lines from the text file, store it in a string array
Dim FileLines() As String = IO.File.ReadAllLines(FilePath)
'make a temporary list of tuples, (5th column, full line)
Dim UnsortedLinesByFifthColumn As New List(Of Tuple(Of String, String))
For Each Line As String In FileLines
'get the string on the fifth column of the line, it looks like your columns are delimited by spaces.
Dim FifthColumnString as String = Line.Split(" ")(4)
'make a tuple representing each line, so we can sort it easily
' Item1 Item2
Dim LineTuple As New Tuple(Of String, String)(FifthColumnString, Line)
UnsortedLinesByFifthColumn.Add(LineTuple)
Next
'use OrderBy and a lambda expression to sort by the string in the fifth column
Dim SortedLinesByFifthColumn As List(Of Tuple(Of String, String)) = UnsortedLinesByFifthColumn.OrderBy(Function(a) a.Item1).ToList()
'print out the lines sorted by the fifth column
For Each SortedLine As Tuple(Of String, String) In SortedLinesByFifthColumn
Dim OriginalLine As String = SortedLine.Item2
Console.WriteLine(OriginalLine)
Next
'stop the program so you can read what was printed to the console
Stop
End Sub
End Module
输入:
SomeTextFile.txt
hello i am who 1
I am who hello 14
am hello who I 13
输出(控制台)
hello i am who 1
am hello who I 13
I am who hello 14
请注意,我假设您要按第五个空格分隔列对行进行排序;如果这不是您要求的,请编辑您的问题,我会更新此答案。