【发布时间】:2020-06-18 13:04:43
【问题描述】:
如何知道具有多个值的字典是否包含特定值?
'Create dictionary
Dim testDictionary As New Dictionary(Of String, Items)
'Code to fill dictionary
'.......................
'.......................
'.......................
'Test if a specific value is contained in dictionary
Dim testValue as String = "TEST"
testDictionary.ContainsValue(testValue) 'This doesn't work
Public Class Items
Public Property Property1 As String
Public Property Property2 As String
Public Sub New()
End Sub
End Class
【问题讨论】:
-
您应该使用 Key 来确定 Dictionary 是否包含特定的 Value,在这种情况下,它也是类对象的 Property 值。你用钥匙干什么?无论如何,您可以检查 Values 集合,例如
Dim theItem = testDictionary.Values.OfType(Of Items).FirstOrDefault(Function(i) i.Property1.Equals("TEST") OrElse i.Property2.Equals("TEST"))。如果您只需要测试是否存在,您可以使用Any()而不是FirstOrDefault()。您应该使用密钥。或其他类型的集合。 -
什么值?这是一个字符串,但字典包含
Itemss。 testValue 应该出现在 Property1 还是 Property2 中?或者两者兼而有之?还是完全不同的东西? -
如果您在
Dictionary中寻找值(而不是键),那么您应该认真考虑一个普通的Dictionary是否是正确的数据结构。 (可能最终您会得出结论,但搜索值是一个巨大的危险信号。)
标签: vb.net dictionary contains