How do I convert a dynamic object to a Dictionary in C# What can I do?
public static void MyMethod(object obj)
{
if (typ
This code securely works to convert Object to Dictionary (having as premise that the source object comes from a Dictionary):
private static Dictionary ObjectToDictionary(object source)
{
Dictionary result = new Dictionary();
TKey[] keys = { };
TValue[] values = { };
bool outLoopingKeys = false, outLoopingValues = false;
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
{
object value = property.GetValue(source);
if (value is Dictionary.KeyCollection)
{
keys = ((Dictionary.KeyCollection)value).ToArray();
outLoopingKeys = true;
}
if (value is Dictionary.ValueCollection)
{
values = ((Dictionary.ValueCollection)value).ToArray();
outLoopingValues = true;
}
if(outLoopingKeys & outLoopingValues)
{
break;
}
}
for (int i = 0; i < keys.Length; i++)
{
result.Add(keys[i], values[i]);
}
return result;
}