我有一个类,其主要类成员为 Dictionary(Of DateTime,CustomClass)
。如果满足某些条件,我想编写一种删除字典元素的方法,类似于.Where(Function(p) p.isTrue)
函数。我发现了有关使用谓词的文档,但没有一个与一个谓词建造有关的文档。这可能吗?
我通常是linq的所有gung-ho,但这是我认为您应该使用for/sext循环通过词典向后迭代并删除't满足您的状况:
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
是的,这是可能的。
只是用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。