2

我有以下对象结构

一个团队有很多团队,一个团队有很多玩家

m_Groups是一组可观察的集合

我试图让团队名称给定一个组名和一个玩家名,我可以为每个人这样做,但在将其转换为 LINQ 时遇到了麻烦:

Dim retVal As String = String.empty  

For Each g In m_Groups
  For Each t In g.Teams
    For Each p In t.Players
      If p.PlayerName.Equals(name) Then
        retVal = t.TeamName
      End If
    Next
  Next
Next
4

3 回答 3

2
Dim teamName = (From group in Groups _
                From team In group.Teams _
                From player In team.Players _
                Where player.PlayerName.Equals(name) _
                Select team.TeamName).FirstOrDefault()

(免责声明:我主要是在猜测上面的 VB 语法。)

另外,我处理像你这样的情况的实际方法是给玩家一个Team属性并在加载后将它们连接一次,而不是每次都进行查找。(假设玩家分配没有改变,双向连接需要一些样板来维护。)

于 2013-03-19T01:53:44.043 回答
1

显然有几种方法可以做到,这就是我想到的

  var team = m_Groups
       .SelectMany(g=>g.Teams)
       .FirstOrDefault(t=>t.Players.Any(p=>p.PlayerName == name));

我希望你能自己把它转换成VB

于 2013-03-18T23:42:57.870 回答
1

通过您的设置,我假设您每次需要搜索特定团队时都会执行 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 回答的影响,有两个细微的变化:

  1. Dim team-> Dim teamName,你不能team在同一个范围内有两个变量。
  2. OP 想要队名,所以Select player变成了Select team.TeamName.
于 2013-03-19T02:06:55.597 回答