VB.net将一个.txt文件放入类列表中,并为该.txt文件的某些索引分配一个属性



我有一个问题,我已经为我的排序程序创建了一个类列表,所以我可以根据名称对项目进行排序。我可以用分配的数据来完成,但我不知道如何从txt文件向类添加数据,也不知道如何在加载文件后为这些项分配属性。

我当前的代码:

Public Class PatientSorter
Public Class Patients
Property Name As String
Property Age As Integer
Property Weight As Double
Property Height As Integer
Public Overrides Function ToString() As String
Return String.Format("{0}: {1} years old, {2} mm, {3} kg", Name, Age, Height, Weight)
End Function
End Class

Public Sub PatientSorter_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim i As Integer
Do While i <= DataEntry.lstPatientArray.Items.Count - 1
lstCurrentData.Items.Add(DataEntry.lstPatientArray.Items(i))
i = i + 1
Loop

End Sub
Private Sub btnSearchForm_Click(sender As Object, e As EventArgs) Handles btnSearchForm.Click
Me.Hide()
Search.Show()
End Sub
Public Sub BubbleSort(ByRef patients As List(Of Patients))
For i = 0 To patients.Count - 2
Dim doneSwap = False
For j = i + 1 To patients.Count - 1
If patients(i).Name > patients(j).Name Then
Dim tmp = patients(j)
patients(j) = patients(i)
patients(i) = tmp
doneSwap = True
End If
Next
If Not doneSwap Then Return
Next
End Sub
Public Sub btnNameSort_Click(sender As Object, e As EventArgs) Handles btnNameSort.Click
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:Data.txt")
Dim patients As New List(Of Patients)

BubbleSort(patients)
End Sub
End Class

txt文件中的一些数据,第一行是姓名,第二行是年龄,第三行是身高,第四行是体重:

Monty Reyes

28

1700

70.7

基尔伯克

45

1800

93.5

我的目标是使用我的bubblesort根据名称对txt文件中的数据进行排序。没有这些数据就无法做到这一点。希望有人能帮助我,或者给我一个线索,告诉我我错过了什么。

使用ReadAllLines而不是ReadAllText将为您提供文件中所有行项目的数组。然后,您可以在该数组中循环,逐行提取数据,以创建和填充Patient对象,然后将其插入到列表中。

Dim patients As New List(Of Patient)
Dim data = System.IO.File.ReadAllLines("C:Data.txt") 'read lines into an array
'loop through the array, incrementing the index by 4 each iteration
For index = 0 To data.Length - 1 Step 4
Dim patient = New Patient() 'create a Patient
'Populate the patient data by accessing the current 4 array indexes
patient.Name = data(index)
patient.Age = data(index + 1)
patient.Weight = data(index + 2)
patient.Height = data(index + 3)
patients.Add(patient) 'add the Patient to the list of Patients 
Next

最新更新