1

如何从对象数组和字符串数组的交集中获取对象集合?

例如,我有一个对象集合(Person 类)和一个字符串数组:

Public Class Person
    Public lastName As String
    Public firstName As String
End Class

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim personArray As List(Of Person)
        Dim p1 As Person = New Person("Bill", "Fitch") : personArray.Add(p1)
        Dim p2 As Person = New Person("Randy", "Roberts") : personArray.Add(p2)
        Dim p3 As Person = New Person("Miles", "Johnson") : personArray.Add(p3)
        Dim p4 As Person = New Person("Sandy", "Smith") : personArray.Add(p4)

        Dim arrayNames() As String = {"Jones", "Roberts", "Smith", "Teague"}

        'The Linq code
        Dim query = From myPerson In personArray
                    Where myPerson.lastName = arrayNames
                    Select myPerson
    End Sub
End Class

当然,Linq 代码不起作用,但 Linq 能做什么?

4

2 回答 2

2

您可以使用包含:

    Dim query = From myPerson In personArray
                Where arrayNames.Contains(myPerson.lastName)
                Select myPerson
于 2013-03-21T19:38:36.320 回答
0

您可以使用联接:

Dim query = From p As Person In personArray
            Join lastName As String In arrayNames On p.lastName Equals lastName
            Select p

这是完整的代码,如果你想测试它(我稍微改变了你的代码,以确保它可以编译)。

Public Class Form1
  Public Class Person
    Public lastName As String
    Public firstName As String
    Sub New(firstName As String, lastName As String)
      Me.lastName = lastName
      Me.firstName = firstName
    End Sub
  End Class

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim personArray As New List(Of Person)({
      New Person("Bill", "Fitch"),
      New Person("Randy", "Roberts"),
      New Person("Miles", "Johnson"),
      New Person("Sandy", "Smith")
    })

    Dim arrayNames() As String = {"Jones", "Roberts", "Smith", "Teague"}

    Dim query = From p As Person In personArray
                Join lastName As String In arrayNames On p.lastName Equals lastName
                Select p
  End Sub
End Class
于 2013-03-21T19:52:03.427 回答