Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Generic Dictionary to different type

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);
like image 835
Nick Avatar asked Mar 31 '09 19:03

Nick


People also ask

Is dictionary a generic type?

The advantage of Dictionary is, it is generic type.

What is TKey and TValue?

In Dictionary<TKey,TValue> TKey is the type of the Key, and TValue is the Type of the Value. It is recommended that you use a similar naming convention if possible in your own generics when there is nore than one type parameter.

Is dictionary generic in C#?

C# - Dictionary<TKey, TValue> The Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no particular order.

Is dictionary generic collection?

NET. C# Dictionary class is a generic collection of keys and values pair of data. The Dictionary class is defined in the System. Collections.


2 Answers

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.

like image 138
mqp Avatar answered Sep 27 '22 20:09

mqp


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));
like image 21
Jhonny D. Cano -Leftware- Avatar answered Sep 27 '22 18:09

Jhonny D. Cano -Leftware-