Home > Net >  Visual Basic Text File
Visual Basic Text File

Time:03-24

I'm currently learning about Visual Basic text files but I came across a problem. I'm supposed to create a text file (Players) with data inside and I have to design a form with listbox to include the players’ names that are more than 30 years old.

This is my current code:

Dim q1 = From itm As String In IO.File.ReadAllLines("Players.txt")
Let Data=itm.Split(","c)
Let fname = Data(0)
Let age = Data(4)
Let newline = fname * " "& age
Where age > 30

For Each itm1 As String in q1
    ListBox1.Items.Add(itm1)
Next

My expected output should show the names of players that are over 30 years old. Thank you in advance to anyone that can help me solve this issue.

CodePudding user response:

You can use linq. For example: assume you have a txt like that

Giuseppe, 30
Pippo, 13
Luca, 32

to extract only over 30 years old you can do...

Dim obj = My.Computer.FileSystem.ReadAllText("Players.txt").Split(vbCrLf).ToList()
Dim ret = (From a In obj Where a.Split(",")(1) > 30 Select a).ToList

The result is

Luca, 32

CodePudding user response:

Best to use a class to define Player. I also made a class Players to hide the file processing from the consumer.

Public Class Player
    Public Property Name As String
    Public Property Age As Integer
End Class

Public Class Players
    Private _list As New List(Of Player)()
    Public ReadOnly Property List As IEnumerable(Of Player)
        Get
            Return _list
        End Get
    End Property
    Public Sub New(path As String)
        Dim lines = File.ReadAllLines(path)
        For Each line In lines
            Dim split = line.Split(","c)
            If split.Count = 2 Then
                _list.Add(New Player() With {.Name = split(0), .Age = Integer.Parse(split(1))})
            End If
        Next
    End Sub
End Class

And use databinding to populate the ListBox

Dim ps = New Players("Players.txt")
Me.ListBox1.DataSource = ps.Items.Where(Function(p) p.Age >= 30).ToList()
Me.ListBox1.DisplayMember = "Name"

If you're not into the whole Players class and Items property, you can still use the Player class, and just do all the processing in your consuming code (it's basically the same thing, but the processing code is not encapsulated in the model).

Dim ps = New List(Of Player)()
Dim lines = File.ReadAllLines("Players.txt")
For Each line In lines
    Dim split = line.Split(","c)
    If split.Count = 2 Then
        ps.Add(New Player() With {.Name = split(0), .Age = Integer.Parse(split(1))})
    End If
Next
Me.ListBox1.DataSource = ps.Where(Function(p) p.Age >= 30).ToList()
Me.ListBox1.DisplayMember = "Name"
  • Related