Suppose I have the following dictionaries:
private Dictionary<int, string> dic1 = new Dictionary<int, string>() { { 1, "a" }, { 2, "b" }, { 3, "c" } } private Dictionary<SomeEnum, bool> dic2 = new Dictionary<SomeEnum, bool>() { { SomeEnum.First, true }, { SomeEnum.Second, false }, { SomeEnum.Third, false } }
I want to convert these two dictionaries to Dictionary<string, object>
For example:
dic1 = new Dictionary<string, object>() { { "1", "a" }, { "2", "b" }, { "3", "c" } } dic2 = new Dictionary<string, object>() { { "First", true }, { "Second", false }, { "Third", false } }
As you can see, the string key of these dictionaries is just a representation of the string previous ones.
The method responsible for the conversion has the following signature:
public static object MapToValidType(Type type, object value) {
I tried the following:
((IDictionary)value).Cast<object>().ToDictionary(i => ...);
But i was passed to the object, so I cannot access the elements of the key or value. To do this, I would need to apply it to the corresponding KeyValuePair<TKey, TValue> , but I do not know the type of TKey or TValue .
Another solution is as follows:
IDictionary dic = (IDictionary)value; IList<string> keys = dic.Keys.Cast<object>().Select(k => Convert.ToString(k)).ToList(); IList<object> values = dic.Values.Cast<object>().ToList(); Dictionary<string, object> newDic = new Dictionary<string, object>(); for(int i = 0; i < keys.Count; i++) newDic.Add(keys[0], values[0]); return newDic;
However, I don't really like this approach, and I'm really looking for a simpler and more friendly single-line LINQ statement.