通过您的设置,我假设您每次需要搜索特定团队时都会执行 LINQ 查询。更好的方法是具有线性结构,例如字典,它具有name
键。
保持接近你在那里的东西,这里有一些代码可以玩:
Option Strict On
Public Class Form1
Class MyGroup
Public Teams As New List(Of MyTeam)
End Class
Class MyTeam
Public Players As New List(Of MyPlayer)
Public TeamName As String
End Class
Class MyPlayer
Public PlayerName As String
End Class
Dim m_Groups As New List(Of MyGroup)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim p As New MyPlayer With {.PlayerName = "Player"}
Dim t As New MyTeam With {.TeamName = "Team", .Players = New List(Of MyPlayer)({p})}
m_Groups.Add(New MyGroup With {.Teams = New List(Of MyTeam)({t})})
Dim name As String = "Player" 'player name to be searched
Dim teamName = (From group In m_Groups _
From team In group.Teams _
From player In team.Players _
Where player.PlayerName.Equals(name) _
Select team.TeamName).FirstOrDefault()
End Sub
End Class
它深受@millimoose 回答的影响,有两个细微的变化:
Dim team
-> Dim teamName
,你不能team
在同一个范围内有两个变量。
- OP 想要队名,所以
Select player
变成了Select team.TeamName
.