VB.NET - Reading a text file containing tab-separa

2019-02-25 09:53发布

问题:

I have a text file containing tab-seperated integers and doubles, e.g.:

5[TAB]0.3[TAB]2.9[TAB]61[TAB]110
8[TAB]1.1[TAB]5.2[TAB]13[TAB]45
1[TAB]0.8[TAB]1.4[TAB]28[TAB]33
...

What I need is a convenient way to access each line as a double array in VB.NET - so that the first array would be [5.0 0.3 2.9 61.0 110.0], the second array would be [8.0 1.1 5.2 13.0 45.0], and so on...

How can this be accomplished using the StreamReader?

回答1:

If it's ok to use a list of lists instead of a list of arrays, you can just do this:

Private Function LoadFile(ByVal filePath As String) As List(Of List(Of Double))
    Dim records As New List(Of List(Of Double))()
    For Each line As String In File.ReadAllLines(filePath)
        Dim values As New List(Of Double)()
        For Each field As String In line.Split(New String() {ControlChars.Tab}, StringSplitOptions.None)
            values.Add(Double.Parse(field))
        Next
        records.Add(values)
    Next
    Return records
End Function

Or, if it must be a list of arrays, you could do this:

Private Function LoadFileToArrays(ByVal filePath As String) As List(Of Double())
    Dim records As New List(Of Double())()
    For Each line As String In File.ReadAllLines(filePath)
        Dim values As New List(Of Double)()
        For Each field As String In line.Split(New String() {ControlChars.Tab}, StringSplitOptions.None)
            values.Add(Double.Parse(field))
        Next
        records.Add(values.ToArray())
    Next
    Return records
End Function

If you need an array of arrays, you could just return records.ToArray(), instead, in that last example. I did not add any code to handle invalid or empty field values, because it wasn't clear, in your question, how you would want to handle those. So, you'll want to add code to handle that appropriately, otherwise, this code will throw an exception in such cases.