我有一个在VB.NET中的哈希表,需要从其值获取键的字符串值。例如,如果我执行以下操作:
hashtable.add("string1","string2")
如果我有"string2",我该如何获取"value1"的值?
你无法直接实现这个功能(至少不能简单地遍历每个值)。需要考虑到多个键可以映射到同一个值的情况:
hashtable.Add("string1", "string2")
hashtable.Add("string3", "string2")
现在如果给定"string2",你会期望返回什么?
如果你真的需要进行“反向”查找,那么最简单的解决方案可能是拥有两个哈希表,一个用于“正向”查找,另一个用于“反向”查找。
正如Dean / codeka所说,您严格来说不能这样做。
但是,您可以像这样做,因为Hashtable的Keys
和Values
处于相同(未指定)的顺序:
Hashtable ht = new Hashtable();
ht.Add("string1", "str2");
ht.Add("string2", "str2");
List<string> keys = new List<string>(ht.Keys.OfType<string>());
string key = ht.Values.OfType<string>()
.Select((htI, i) => new { Key = keys[i], Value = htI })
.Where(htKVP => htKVP.Value == "str2")
.Select(htKVP => htKVP.Key)
.FirstOrDefault();
然而,最好使用 Dictionary<string, string>
,因为它是泛型类型,并且让您更容易地使用 Linq。
转换为 VB.NET 如下:
Dim ht as new Hashtable()
ht.Add("string1", "str2")
ht.Add("string2", "str2")
Dim keys as new List(Of String)(ht.Keys.OfType(Of String)())
Dim key as String = ht.Values.OfType(Of String)() _
.Select(Function(htI, i) New With { .Key = keys(i), .Value = htI }) _
.Where(Function(htKVP) htKVP.Value = "str2") _
.Select(Function(htKVP) htKVP.Key) _
.FirstOrDefault()
但是我会再次从以下开始:
Dim dt as New Dictionary(Of String, String)
你可以将它作为扩展方法添加,像这样:
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Function FirstKeyForValue(ByVal Hashtable as ht, ByVal value As String) As String
return ht.Values.OfType(Of String)() _
.Select(Function(htI, i) New With { .Key = keys(i), .Value = htI }) _
.Where(Function(htKVP) htKVP.Value = "str2") _
.Select(Function(htKVP) htKVP.Key) _
.FirstOrDefault()
End Function
End Module
有比Matt的答案更简单的方法。您可以在哈希表上执行linq。 当然,下面的示例代码可以修改为使用Hashtable变量中使用的正确类型,因为Key和Value都可以是任何类型:
Public Class HashtableTest
Private Lookup As New Hashtable
Private Sub New()
Lookup("Key1") = "Value1"
Lookup("Key2") = "Value2"
End Sub
Public Sub Test()
MsgBox(GetKey("Value2"))
End Sub
Public Function GetKey(Value As String) As String
Dim FoundKey As String = ""
If Lookup.ContainsValue(Value) Then
FoundKey = (From Key As String In Lookup.Keys.Cast(Of String) Where Lookup(Key).ToString() = Value Select Key).FirstOrDefault()
End If
Return FoundKey
End Function
End Class