【问题标题】:Extract part of a text file for usage in vb.net提取文本文件的一部分以在 vb.net 中使用
【发布时间】:2013-09-30 11:47:03
【问题描述】:
好的。我需要将一些记录存储在一个文件中,即data.dat。
文件中的记录按日期值排序。每个记录块都以其日期值开头,并带有$ 符号,表示新的记录块从这里开始,并以“#”符号结束,表示记录块的结束。
一个记录块的样本是:
$22/08/2013
(data)
(data)
(data)
#
文件 data.dat 包含几个这样的块,我如何提取文件中的每个块,使用 vb.net 将每个块存储在一个数组中?
【问题讨论】:
标签:
arrays
vb.net
substring
【解决方案1】:
我会使用List(Of T) 而不是数组。您可以创建一个自定义类:
Class Record
Public Property DateValue As DateTime
Public Property Data As New List(Of String)
End Class
这是一个从文件初始化列表的可能循环:
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】:
在我看来,元组四重奏已经为此做好了准备。
Dim Record As New List(Of Tuple(Of DateTime, String, String, Integer))
然后每个字段都可以通过它的项目编号访问:
Record(0).Item1