public static class ObjectToDictionaryHelper { public static IDictionary<string, T> ToDictionary<T>(object source) { if (source == null) throw new ArgumentNullException("source", "Cannot convert null to a dictionary."); var dictionary = new Dictionary<string, T>(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source)) AddPropertyToDictionary<T>(property, source, dictionary); return dictionary; } private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary) { object value = property.GetValue(source); if (value is T) dictionary.Add(property.Name, (T)value); } }
401800cookie-checkC# object to dictionary