I have a file containing the first name, second name and age of a person:
John, Smith, 35
Andrew, Jacobs, 52
I have split up the first name, second name and age and put them into arrays.
Becuase I know that there are 2 people (I set the array size to 1) , I am using the following 'for' loop:
For x = 0 to 1
textbox1.text = textbox1.text + first_name(x)
Next
I want to change this to the following:
For x = 0 to however long the file is
textbox1.text = textbox1.text + first_name(x)
Next
However, when I try to use 0 to first_name.length it doesn't work.
If what you want to do is put the contents of a line-delimited file into a VB string array, why don't you just let the file tell you how many lines there are?
Like:
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
How about creating a Person class - then you won't have separate arrays to carry around.
Try this:
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
Usage:
Dim people = ReadPeople("c:\people.txt")
If I were you I would just make things simple as possible.
Try this:
textbox1.Text = _
String.Join("", File.ReadAllLines("") _
.Select(Function(x) x.Split(","C)(0).Trim()))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.