好的,所以这可能是一个简单/愚蠢的问题,但非常感谢帮助。
现在,我正在通过以下方式将类添加到列表中:
Public RacersArray As New List(Of Racer)
...
Dim tempRacer As New Racer()
With tempRacer 'create data that is to be 'add' or 'edit'
.Name = InpName.Text
.CleatSize = InpCleatSize.Text
.SkillLevel = InpSkillLevel.Text
.Height = InpHeight.Text
.Team = InpPreferredTeam.Text
End With
RacersArray.Add(tempRacer)
我正在尝试通过执行以下操作来引用此列表中的项目:
RacersArray.IndexOf(<Name>)
但很明显,如果他们都有相同的项目名称'tempRacer',那将无效。
我有强烈的感觉,这不是我打算这样做的方式。
感谢您的帮助!!
答案 0 :(得分:1)
您可以通过迭代访问它们。
For Each r As Racer In RacersArray
'Access properties here..
MessageBox(r.SkillLevel & " " & r.Team)
Next r
编辑:如果你想要一个特定的名字,那么
For Each r As Racer In RacersArray
If r.Name = "Desired Name" Then
'Access properties here..
MessageBox(r.SkillLevel & " " & r.Team)
Exit For
End If
Next r
作为一项功能
Private Function GetRacer(Byval RacersArray As List(Of Racer), Byval Name As String) As Racer
Dim racerInfo As Racer
For Each r As Racer In RacersArray
If r.Name = Name Then
racerInfo = r
Exit For
End If
Next r
Return racerInfo
End Function
答案 1 :(得分:1)
使用简单的for循环:
for i as integer =0 to RacersArray.Count -1
'use RacersArray(i) to access item
next
答案 2 :(得分:1)
我认为最简单的方法是在Shared
类中添加Racer
函数。 (您可以使用Predicate
来支持内置的List(Of ).Find
方法,但它更复杂一些)
Sub Demo()
Dim RacersArray As New List(Of Racer)
RacersArray.Add(New Racer With {.Name = "Alpha", .CleatSize = "1", .SkillLevel = "Novice", .Height = "180", .Team = "Bananas"})
RacersArray.Add(New Racer With {.Name = "Beta", .CleatSize = "2", .SkillLevel = "Journeyman", .Height = "160", .Team = "Apples"})
RacersArray.Add(New Racer With {.Name = "Gamma", .CleatSize = "3", .SkillLevel = "Expert", .Height = "200", .Team = "Apples"})
RacersArray.Add(New Racer With {.Name = "Delta", .CleatSize = "4", .SkillLevel = "Expert", .Height = "1950", .Team = "Bananas"})
Dim rcrFind As Racer = Racer.FindName(RacersArray, "Beta")
If rcrFind Is Nothing Then
MsgBox("Not found")
Else
MsgBox(rcrFind.Team)
End If
End Sub
Class Racer
Public Property Name As String
Public Property CleatSize As String
Public Property SkillLevel As String
Public Property Height As String
Public Property Team As String
Public Shared Function FindName(l As List(Of Racer), name As String) As Racer
For Each r As Racer In l
If r.Name = name Then Return r
Next r
Return Nothing
End Function
End Class
答案 3 :(得分:1)
您可以使用LINQ ...
Matches = (From r In RacersArray Where r.Name = "{name you're looking for}")
匹配将包含零个或多个具有您指定名称的Racers。
您可以通过向表达式添加其他属性来获得更具体的信息。
Matches = (From r In RacersArray Where r.Name = "Some Name" And r.Team = "Some Team")
我同意Zaggler,您可能需要考虑添加识别属性或密钥,以确保每个Racer都是唯一的。
另外,我建议你放弃&#34; Array&#34;在任何列表名称中。 &#34;赛车&#34;足以让人知道而不是暗示更多那个。