13

Is there a quick way to convert a Generic Dictionary from one type to another

I have this

IDictionary<string, string> _commands;

and need to pass it to a function that takes a slightly different typed Dictionary

public void Handle(IDictionary<string, Object> _commands);
Nick
  • 5,848
  • 4
  • 28
  • 33

4 Answers4

23

I suppose I would write

Handle(_commands.ToDictionary(p => p.Key, p => (object)p.Value));

Not the most efficient thing in the world to do, but until covariance is in, that's the breaks.

mqp
  • 70,359
  • 14
  • 95
  • 123
  • The ToDictionary method requires 'using System.Linq;' (I was scratching my head for a minute or two). – danw Nov 19 '13 at 01:10
1

maybe this function can be useful for you

IEnumerable<KeyValuePair<string, object>> Convert(IDictionary<string, string> dic) {
    foreach(var item in dic) {
        yield return new KeyValuePair<string, object>(item.Key, item.Value);
    }
}

And you will call it like so:

Handle(Convert(_commands));
Jhonny D. Cano -Leftware-
  • 17,663
  • 14
  • 81
  • 103
0

Can't you use

Dim myDictionary AS New Dictionary(Of Object, Object)

This would then be able to accept any types

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
0

could something like this do?

Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1, "One");
dict.Add(2, "Two");
dict.Add(3, "Three");
dict.Add(4, "Four");
dict.Add(5, "Five");

object dictObj = (object)dict;

IDictionary temp = (IDictionary)dictObj;

Dictionary<int, object> objs = new Dictionary<int, object>();

foreach (DictionaryEntry de in temp)
{
    objs.Add((int)de.Key, (object)de.Value);
}