これを行うには多くの方法がありますが、他の方法よりも読みやすいものがあります。
まず、私は、例えば、When should I use a struct instead of a class?を参照してください(StudentDetails
クラスの代わりの構造になるだろう。
第三の例で使用されるように今、あなたがクラスを持っていることを、あなたは、それをパラメータで新しいコンストラクタを与えることができますここではそれはVS2015で導入されましたので、あなたは、あなたが代わりにString.Format("{0} {1} {2}", Me.Name, Me.School, Me.Location)
を使用することができます以前のバージョンを使用している場合
:
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()
方法で$
文字列フォーマッタを使用しました。
StudentDetails
という名前の注記として、StudentName
,StudentSchool
およびStudentLocation
の「学生」は冗長です。
これは単なるサンプルデータです。実際のデータは生徒の詳細ではありません。しかし、私はあなたのヒントを書き留めておき、構造の代わりにクラスを使うべき理由を説明してくれてありがとう。 – Ian