How do I convert a dynamic object to a Dictionary in C# What can I do?
Dictionary
public static void MyMethod(object obj) { if (typ
I use this helper:
public static class ObjectToDictionaryHelper { public static IDictionary ToDictionary(this object source) { return source.ToDictionary(); } public static IDictionary ToDictionary(this object source) { if (source == null) ThrowExceptionWhenSourceArgumentIsNull(); var dictionary = new Dictionary(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source)) AddPropertyToDictionary(property, source, dictionary); return dictionary; } private static void AddPropertyToDictionary(PropertyDescriptor property, object source, Dictionary dictionary) { object value = property.GetValue(source); if (IsOfType(value)) dictionary.Add(property.Name, (T)value); } private static bool IsOfType(object value) { return value is T; } private static void ThrowExceptionWhenSourceArgumentIsNull() { throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null."); } }
the usage is just to call .ToDictionary() on an object
.ToDictionary()
Hope it helps.