Reputation: 13
I am loading a .txt file that contains around a thousand names in a firstName:lastName format. I only need the firstnames for what I'm doing right now. How can I strip the entire list, which is displayed in a listbox, and display first names only?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:temp"
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox2.Text = OpenFileDialog1.FileName.ToString()
ListBox1.Items.AddRange(System.IO.File.ReadAllLines(TextBox2.Text))
End Sub
Upvotes: 1
Views: 45
Reputation: 8160
Use String.Split
to break each line apart at the delimiter and use the first part returned:
ListBox1.Items.AddRange(
System.IO.File.ReadLines(TextBox2.Text).Select(
Function(x) x.Split(":"c)(0)
).ToArray()
)
I used ReadLines
instead of ReadAllLines
, since it may be a little more efficient, but it looks like AddRange
needs an array anyway, hence the ToArray
call.
However, it really depends on what you are going to do once you have the items in the list. It may be better to create a class for the full names and read the file into a list of those, and then bind using DataSource
and DisplayMember
.
Upvotes: 1
Reputation: 15774
You can split each line into a sub-array, and return the first element into a new array
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox2.Text = OpenFileDialog1.FileName.ToString()
ListBox1.Items.AddRange(
System.IO.File.ReadAllLines(TextBox2.Text).
Select(Function(l) l.Split(":"c).FirstOrDefault()).
ToArray())
End Sub
Upvotes: 1