有很多方法可以做到這一點,比其他人更容易閱讀。
首先,我會做StudentDetails
一類,而不是一個結構(例如,參見When should I use a struct instead of a class?。
現在你有一個類,你可以給它一個帶參數的新構造,如在第三例中使用在這裏:
Option Infer On
Option Strict On
Module Module1
Public Class StudentDetails
Public Name As String
Public School As String
Public Location As String
Public Sub New()
' empty constuctor
End Sub
Public Sub New(name As String, school As String, location As String)
Me.Name = name
Me.School = school
Me.Location = location
End Sub
' make it easy to represent StudentDetails as a string...
Public Overrides Function ToString() As String
Return $"{Me.Name} {Me.School} {Me.Location}"
End Function
End Class
Sub Main()
Dim list1 As New List(Of String) From {"Adam", "Betty", "Charles", "Wilma"}
Dim list2 As New List(Of String) From {"Ace", "Best", "Classy", "Wacky"}
Dim list3 As New List(Of String) From {"Attic", "Basement", "Cellar", "Windowledge"}
' a not-very tidy example using Zip:
Dim StudentDetailsList = list1.Zip(list2, Function(a, b) New With {.name = a, .school = b}).Zip(list3, Function(c, d) New StudentDetails With {.Name = c.name, .School = c.school, .Location = d}).ToList()
' one way of writing out the StudentDetailsList...
For Each s In StudentDetailsList
Console.WriteLine(s.ToString())
Next
StudentDetailsList.Clear()
' a bit cleaner using a loop:
For i = 0 To list1.Count() - 1
StudentDetailsList.Add(New StudentDetails With {
.Name = list1(i),
.School = list2(i),
.Location = list3(i)})
Next
' another way of writing out the StudentDetailsList...
Console.WriteLine(String.Join(vbCrLf, StudentDetailsList))
StudentDetailsList.Clear()
' easy to write with a New constructor, but not necessarily as easy to read as the previous example:
For i = 0 To list1.Count() - 1
StudentDetailsList.Add(New StudentDetails(list1(i), list2(i), list3(i)))
Next
Console.WriteLine(String.Join(vbCrLf, StudentDetailsList))
Console.ReadLine()
End Sub
End Module
我曾經在.ToString()
方法$
字符串格式:它與VS2015推出,因此,如果您使用的是較早的版本,你可以使用String.Format("{0} {1} {2}", Me.Name, Me.School, Me.Location)
代替
。
作爲關於命名StudentDetails
的屬性的說明,StudentName
,StudentSchool
和StudentLocation
中的「學生」是多餘的。
這只是一個示例數據。真實數據不是學生的細節。但是,我會記下你的提示,並感謝你解釋爲什麼我應該使用類而不是結構。 – Ian