How can I get all KeyValuePairs contained in Dictonary <?,?>?

I have an object that is a Dictionary of an unknown type (i.e. I do not know the type of key and value)

I want to get all my values ​​in order to access them by index.

So what I want to do is something like this:

Dictionary<object, object> d = (Dictionary<object, object>)obj; // cast error
l = new List<KeyValuePair<object,object>>();
foreach (KeyValuePair<object, object> k in d)
   l.Add(new KeyValuePair<object,object>(k.Key, k.Value));

However, as expected, the runtime will not allow me to switch to the dictionary <object, object>.

Is there a way to do this in .net 3.0? (e.g. using reflection?)

+3
source share
3 answers

obj Dictionary<object, object>, Dictionary<object, object>. , object object. #, . T object, List<T> List<object>.

:

void ModifyList<List<object> list)
{
   for (int i=0; i<list.Count; i++)
   {
      list[i] = list[i].ToString();
   }
}

List<int> List<object>, List<int> , - .

, # 4.0 . .

, :

List<KeyValuePair<object, object>> list = d.AsEnumerable()
   .Select(x => new KeyValuePair<object, object>(x.Key, x.Value))
   .ToList();
+5

Dictionary<,> IDictionary ( ), :

    IDictionary data = ...
    foreach (DictionaryEntry de in data)
    {
        Console.WriteLine(de.Key + ": " + de.Value);
    }
+15

:


foreach (object key in d.keys)
{
 l.Add(new KeyValuePair(key, d[key]);
}
0

Source: https://habr.com/ru/post/1714166/


All Articles