vb.net - 从添加到字典 vb.net 中跳过文本块
问题描述
我想知道是否有一种方法可以读取文本文件,可以说内容如下:
商店 - 001P 所有者 - 格雷格 价格 - 45000 员工 - 30 商店 - 002 业主-仁 价格 - 34400
现在假设我只想处理商店编号包含 P 的块中的商店信息。有没有办法读取文本文件以检查分隔符后的 P,然后跳到“存储”在文本文件中?我试图找到哪个功能最好,因为您可以使用不同的语言 GoTo 功能,但我在这方面找不到任何东西。
这是我当前代码的片段:
Dim columnV As New Dictionary(Of String, Integer)
Dim descriptionV As String
Dim quantityV As Integer
For Each totalLine As String In MyData
descriptionV = Split(totalLine, "-")(0)
quantityV = Split(totalLine, "-")(1)
If columnV.ContainsKey(descriptionV) Then
columnV(descriptionV) = colSums(descriptionV) + quantityV
Else
columnV.Add(descriptionV, quantityV)
End If
'Next
解决方案
似乎一条记录可以跨多行表示,但不是定义的多行数(例如,001P 超过 4 行,但 002 超过 3 行)。
它也看起来好像该线代表某种{property} - {value}
格式的数据。
我要做的第一件事是创建一个类来代表您的记录。
第二件事是从文本文件中获取每一行并迭代它们。
第三件事是获取传入的信息并将其转换为您的自定义类,该类将添加到列表中。
最后一件事是过滤商店不包含字母“P”的列表。
这是代码,在行动:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Module Module1
Public Sub Main()
IO.File.WriteAllLines("test.txt", {
"Store - 001P",
"Owner - Greg",
"Price - 45000",
"Employees - 30",
"Store - 002",
"Owner - Jen",
"Price - 34400"
})
Dim lines() As String = IO.File.ReadAllLines("test.txt")
Dim stores As List(Of Store) = ConvertLinesToStores(lines)
Dim storesWithP() As Store = stores.Where(Function(s) s.StoreId.Contains("P")).ToArray()
Console.WriteLine("Stores with P: ")
Console.WriteLine(String.Join(Environment.NewLine, storesWithP.Select(Function(s) s.StoreId).ToArray()))
End Sub
Private Function ConvertLinesToStores(ByVal lines() As String) As List(Of Store)
Dim stores As New List(Of Store)
Dim item As Store
For Each line As String In lines
Dim parts() As String = line.Split(" - ")
If (lines.Length < 3) Then
Continue For
End If
Dim propertyName As String = parts(0)
Dim propertyValue As String = parts(2)
Dim employeeCount As Integer
If (propertyName = "Store") Then
If (item IsNot Nothing) Then
stores.Add(item)
End If
item = New Store() With {.StoreId = propertyValue}
ElseIf (propertyName = "Owner") Then
item.Owner = propertyValue
ElseIf (propertyName = "Price") Then
item.Price = propertyValue
ElseIf (propertyName = "Employees" AndAlso Integer.TryParse(propertyValue, employeeCount)) Then
item.EmployeeCount = employeeCount
End If
Next
If (item IsNot Nothing) Then
stores.Add(item)
End If
Return stores
End Function
End Module
Public Class Store
Public Property StoreId As String
Public Property Owner As String
Public Property Price As Integer
Public Property EmployeeCount As Integer
End Class
小提琴:现场演示
推荐阅读
- c++ - 如何将 obj 附加到静态库?
- python - 用于传输文件的 Python TCP 服务器/客户端
- javascript - Material UI Autocomplete - 禁用键盘输入(在移动设备上)
- classification - Weaviate 自动分类过程的性能如何?
- asp.net-web-api - 基于参数注册和解析请求的依赖(Autofac WEB API)
- javascript - ReactNative Flatlist 中的 onEndReachedThreshold 参数包括页眉和页脚组件
- javascript - Vuejs Datepicker 启用禁用的元素
- javascript - 另存为 JavaScript - HTML 到 WORD
- python - 如何从 Python 向游戏发送方向盘/操纵杆输入?
- mysql - 无法从 VPS 连接到 MySQL 服务器,但可以从桌面连接