Trying to make a multivalue dictionary that inherits from Dictionary - C# to VB conversion

StackOverflow https://stackoverflow.com/questions/13873135

  •  07-12-2021
  •  | 
  •  

Question

Hi I am trying to convert this C# code to VB

class MultiValueDictionary<TKey, TValue> : Dictionary<TKey, List<TValue>>
{

   public void Add(TKey key, TValue value)
   {
      if(!ContainsKey(key))
         Add(key, new List<TValue>());
      this[key].Add(value);
   }
}

The result looks like this:

Class MultiValueDictionary(Of TKey, TValue)
    Inherits Dictionary(Of TKey, List(Of TValue))

    Public Sub Add(key As TKey, value As TValue)
        If Not ContainsKey(key) Then
            Add(key, New List(Of TValue)())
        End If
        Me(key).Add(value)
    End Sub
End Class

But it gives an error on the line:

Add(key, New List(Of TValue)())

Value of type 'System.Collections.Generic.List(Of TValue)' cannot be converted to 'TValue'.

I am not really that clear about the TKey TValue notation, can somebody explain what this error is telling me? What should it read instead?

Thanks in advance

Était-ce utile?

La solution

First, better inherit interface rather than a list itself.

... : Dictionary<TKey, IList<TValue>>

Second, your Add mthod calling seems to call itself. Try calling base' method.

MyBase.Add(key, New List(Of TValue)())

Third, why don't you just use Lookup<,>? Its so simple to group elements by keys.

Autres conseils

Try explicitly calling the method on the base class instead:

MyBase.Add(key, New List(Of TValue)())

The code conversion utility you used does not allow for VB's suckiness :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top