使用VB.NET的DataTable.Rows.Find的通用列表等价物?

Jos*_*ola 1 vb.net .net-2.0

我正在将DataTables转换为通用列表,并且需要一种快速简便的方法来实现Find函数.看来我将不得不使用Predicate.经过进一步调查,我似乎仍然无法重新创建功能.我有这个谓词......

Private Function ByKey(ByVal Instance As MyClass) As Boolean
    Return Instance.Key = "I NEED THIS COMPARISON TO BE DYNAMIC!"
End Function
Run Code Online (Sandbox Code Playgroud)

然后像这样称呼它......

Dim Blah As MyClass = MyList.Find(AddressOf ByKey)
Run Code Online (Sandbox Code Playgroud)

但我没有办法将一个关键变量传递给这个谓词进行比较,就像我以前用DataTable做的那样......

Dim MyRow as DataRow = MyTable.Rows.Find(KeyVariable)
Run Code Online (Sandbox Code Playgroud)

如何在VB.NET中设置谓词委托函数来实现这一目标?

不建议使用LINQ或lambdas,因为这是关于.NET 2.0版的问题.

Joe*_*orn 5

只需将谓词放在类实例中:

Public Class KeyMatcher
    Public Sub New(ByVal KeyToMatch As String)
       Me.KeyToMatch = KeyToMatch
    End Sub

    Private KeyToMatch As String

    Public Function Predicate(ByVal Instance As MyClass) As Boolean
       Return Instance.Key = KeyToMatch
    End Function
End Class
Run Code Online (Sandbox Code Playgroud)

然后:

Dim Blah As MyClass = MyList.Find(AddressOf New KeyMatcher("testKey").Predicate)
Run Code Online (Sandbox Code Playgroud)

我们甚至可以有点想象,并使这个通用:

Public Interface IKeyed(Of KeyType)
    Public Key As KeyType
End Interface

Public Class KeyMatcher(Of KeyType)
    Public Sub New(ByVal KeyToMatch As KeyType)
       Me.KeyToMatch = KeyToMatch
    End Sub

    Private KeyToMatch As KeyType

    Public Function Predicate(ByVal Instance As IKeyed(Of KeyType)) As Boolean
       Return Instance.Key = KeyToMatch
    End Function
End Class
Run Code Online (Sandbox Code Playgroud)

然后使您的MyClass类型实现新的IKeyed接口