Extract part of a text file for usage in vb.net

心不动则不痛 提交于 2020-01-17 18:41:09

问题


Ok. I need to store some records in a file namely data.dat. Records in the file are sorted by date values. Each block of record starts with its date value along with a $ sign to indicate that a new block of record starts here and ends with a "#" sign to indicate end of the record block.

A sample of a record block would be:

$22/08/2013
(data)
(data)
(data)
#

The file data.dat contains several blocks like this, how can I extract each block in the file storing each in an array using vb.net?


回答1:


Instead of an array i would use a List(Of T). You could create a custom class:

Class Record
    Public Property DateValue As DateTime
    Public Property Data As New List(Of String)
End Class

Here's a possible loop to initialize the list from your file:

Dim allData As New List(Of Record)
Dim currentRecord As Record = Nothing
Dim currentData As List(Of String) = Nothing
For Each line In File.ReadLines("data.dat")
    If line.StartsWith("$") Then
        Dim dt As DateTime
        If Date.TryParse(line.Substring(1), dt) Then
            currentRecord = New Record()
            currentRecord.DateValue = dt
            currentData = New List(Of String)
            currentRecord.Data = currentData
        End If
    ElseIf currentRecord IsNot Nothing Then
        If line.EndsWith("#") Then
            allData.Add(currentRecord)
        Else
            currentData.Add(line)
        End If
    End If
Next



回答2:


It looks to me a Tuple quartet would be ready made for this.

Dim Record As New List(Of Tuple(Of DateTime, String, String, Integer))

Then each field can be accessed by it's item number:

Record(0).Item1


来源:https://stackoverflow.com/questions/19093424/extract-part-of-a-text-file-for-usage-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!