Using KeyValuePair in VB.NET for a reverse lookup capable dictionary (example hint in C# needs converting)
I'm currently on a VB.NET project and wish to use a KeyValuePair to facilitate a reverse lookup.
I've found a great example in C# here: http://www.dreamincode.net/forums/showtopic78080.htm, however I am having a small problem converting to VB.NET (both manually and using a translator (online carlosag)). For example the syntax I would expect in the Add method is as follows:
Public Sub Add(ByVal key As TKey, ByVal value As 开发者_JS百科TValue)
Me.Add(New KeyValuePair(Of Tkey(key, value))
End Sub
Whereas this tells me "Too few type arguments to 'System.Collections.Generic.KeyValuePair(Of TKey, TValue)'"
Any assistance would sure be helpful (indeed as would a full translation of the example including anon methods :D.
I ran the example you referred to through the tool I usually use to convert C# to VB.NET at www.developerfusion.co.uk/tools
Imports System
Imports System.Collections.Generic
Imports System.Text
Namespace ConsoleApplication1
Class PairCollection(Of TKey, TValue)
Inherits List(Of KeyValuePair(Of TKey, TValue))
Public Sub Add(ByVal key As TKey, ByVal value As TValue)
Me.Add(New KeyValuePair(Of TKey, TValue)(key, value))
End Sub
Public Function FindByKey(ByVal key As TKey) As List(Of KeyValuePair(Of TKey, TValue))
Return Me.FindAll(Function(ByVal item As KeyValuePair(Of TKey, TValue)) (item.Key.Equals(key)))
End Function
Public Function FindByValue(ByVal value As TValue) As List(Of KeyValuePair(Of TKey, TValue))
Return Me.FindAll(Function(ByVal item As KeyValuePair(Of TKey, TValue)) (item.Value.Equals(value)))
End Function
End Class
Class Program
Private Shared Sub Main(ByVal args As String())
Dim menu As New PairCollection(Of String, Double)()
menu.Add("Burger", 3.5R)
menu.Add("Hot Dog", 2.25)
menu.Add("Fries", 1.75)
Console.WriteLine(menu.FindByKey("Fries")(0))
Console.ReadLine()
End Sub
End Class
End Namespace
As you can see, the Add() method comes out very slightly differently to yours.
1- As kevinw pointed out, your original code is just wrong, it should be:
Me.Add(New KeyValuePair(Of TKey, TValue)(key, value))
2- The code above should insert a new KeyValuePair
in a PairCollection
which inherits from List(Of KeyValuePair)
. If it doesn't work, there's a good chance that your Inherits line is wrong. According to the error, the Add
method expects a key, not a KeyValuePair
... maybe your inherited from a Dictionary
instead of a List
?
Resolved by making the Add method Overloads as such:
Public Overloads Sub Add(ByVal key As TKey, ByVal value As TValue)
Me.Add(New KeyValuePair(Of TKey, TValue)(key, value))
End Sub
Strange that although MyBase.Add works (found via a decompile in Reflector) Me didn't (despite "this" working in C#). I guess I put this down to a quirk in VB.NET?
Thanks Kevinw and Meta-Knight. Original code was wrong, but I was inheriting from List all along.
精彩评论