我有一个包含姓名,姓名和年龄的文件:
John, Smith, 35
Andrew, Jacobs, 52
我将第一个名字,第二个名字和年龄分开并将它们放入数组中。
因为我知道有2个人(我将数组大小设置为1),我使用以下'for'循环:
For x = 0 to 1
textbox1.text = textbox1.text + first_name(x)
Next
我想将此更改为以下内容:
For x = 0 to however long the file is
textbox1.text = textbox1.text + first_name(x)
Next
但是,当我尝试使用0到first_name.length时,它不起作用。
答案 0 :(得分:2)
如果您要做的是将行分隔文件的内容放入VB字符串数组中,为什么不让文件告诉您有多少行?
像:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim listOfPeople As String()
listOfPeople = System.IO.File.ReadAllLines("C:\\Temp\\file.txt")
For i As Integer = 0 To listOfPeople.Length - 1
Console.WriteLine(listOfPeople(i))
Dim person As String = listOfPeople(i)
Dim personAttributes As String() = person.Split(",")
For j As Integer = 0 To personAttributes.Length - 1
' do something with the attribute
Next
Next
End Sub
答案 1 :(得分:1)
如何创建Person类 - 那么你就不会有单独的数组来携带。
试试这个:
Public Class Person
Public FirstName As String
Public LastName As String
Public Age As Integer
End Class
Public Function ReadPeople(filePath As String) As Person()
Return (From record In IO.File.ReadAllLines(filePath)
Let Terms = record.Split(","c)
Select New Person With {.LastName = Terms(0), .FirstName = Terms(1), .Age = CInt(Terms(2))}) _
.ToArray
End Function
用法:
Dim people = ReadPeople("c:\people.txt")
答案 2 :(得分:0)
如果我是你,我会尽可能简单。
试试这个:
textbox1.Text = _
String.Join("", File.ReadAllLines("") _
.Select(Function(x) x.Split(","C)(0).Trim()))