2016-07-02 15 views
0

私はメモ帳から行を読み込んでいます。 ビジュアルベーシックでソート機能を使ってソートすると、結果が正確ではないことがわかります。vb.netの特定の列を並べ替える

For example 
hello i am who 1 
I am who hello 14 
am hello who I 13 

5番目の列を並べ替える必要があります。どのように視覚的な基本でそれを行うのですか?

+0

まず、メモ帳の5番目の列は常に数字ですか? 第2に、それらは複数の文字列です。ファイルが大きくなく、各行から正確な5番目の文字を並べ替えるだけの場合は、それらの文字列を文字列配列に入れてそこからソートすることをお勧めします。 – HaPhan

答えて

0

あなたは,:例えば、タプルのリストとして、テキストファイルからデータをパースして、5番目の列でソートする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 

行をで5番目に並べ替えることを前提としています。の区切りは、列です。これがあなたの質問ではない場合は、あなたの質問を編集してください。私はこの回答を更新します。

関連する問題