Created
January 27, 2011 15:53
-
-
Save jarrettmeyer/798667 to your computer and use it in GitHub Desktop.
C# convert an object to a dictionary of its properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ObjectToDictionaryHelper | |
{ | |
public static IDictionary<string, object> ToDictionary(this object source) | |
{ | |
return source.ToDictionary<object>(); | |
} | |
public static IDictionary<string, T> ToDictionary<T>(this object source) | |
{ | |
if (source == null) | |
ThrowExceptionWhenSourceArgumentIsNull(); | |
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 (IsOfType<T>(value)) | |
dictionary.add(property.Name, (T)value); | |
} | |
private static bool IsOfType<T>(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."); | |
} | |
} |
Just a typo needs to be fixed
dictionary.add(property.Name, (T)value);
should be
dictionary.Add(property.Name, (T)value);
Line 24
Thanks
Neat helper, very useful.
Thanks!
干净整洁, 赞
Hi Jarret and community, thanks!
I follow this example to make it useful to multiple records on Dictionary and/or the source object comes from a Dictionary:
https://stackoverflow.com/a/52961405/10549791
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
C# Dictionary Exmaples..
http://csharp.net-informations.com/collection/dictionary.htm
c# tutorial