using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace TEAMModelOS.SDK.Helper.Common.CollectionHelper { 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."); } } }