具有函数/谓词参数的类方法

时间:2017-09-22 15:56:37

标签: vb.net methods predicate

我有一个类,其主要成员是Dictionary(Of DateTime,CustomClass)。我想写一个方法,如果满足某些条件,删除字典的元素,类似于.Where(Function(p) p.isTrue)函数。我找到了有关使用谓词的文档,但没有关于使用谓词构建的文档。这可能吗?

2 个答案:

答案 0 :(得分:0)

对于LINQ,我通常都是gung-ho,但是我认为你应该使用For / Next循环向后遍历Dictionary并删除不符合你条件的项目:

Public Class Foo

    'Primary class member
    Public Property Bar As Dictionary(Of DateTime, Foo)

    'Remove method based on some condition (you may want to pass a parameter here too)
    Public Sub Remove()
        'Use a For/Next loop backwards
        For index As Integer = Me.Bar.Keys.Count - 1 To 0 Step -1
            'Check for if the condition is met and then remove the item by its index
            'If ... Then
            '    Me.Bar.Remove(Me.Bar.ElementAt(index).Key)
            'End If
        Next
    End Sub

    Sub New()
        Me.Bar = New Dictionary(Of DateTime, Foo)
    End Sub

End Class

答案 1 :(得分:0)

是的,这是可能的。

只需声明一个带有Func(Of...)参数的方法,该方法代表条件:

Public Sub RemoveElementIf(condition As Func(Of KeyValuePair(Of DateTime, Foo), Boolean))

    If condition IsNot Nothing Then Bar = Bar.Where(Function(x) condition(x))

End Sub

然后你可以在内部使用LINQ。