Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created January 27, 2011 15:53
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jarrettmeyer/798667 to your computer and use it in GitHub Desktop.
Save jarrettmeyer/798667 to your computer and use it in GitHub Desktop.
C# convert an object to a dictionary of its properties
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))
{
object value = property.GetValue(source);
if (IsOfType<T>(value))
{
dictionary.Add(property.Name, (T)value);
}
}
return dictionary;
}
private static bool IsOfType<T>(object value)
{
return value is T;
}
private static void ThrowExceptionWhenSourceArgumentIsNull()
{
throw new NullReferenceException("Unable to convert anonymous object to a dictionary. The source anonymous object is null.");
}
}
@nivabeath
Copy link

@shaahink
Copy link

Just a typo needs to be fixed
dictionary.add(property.Name, (T)value);
should be
dictionary.Add(property.Name, (T)value);
Line 24

Thanks

@axedre
Copy link

axedre commented Jun 24, 2016

Neat helper, very useful.
Thanks!

@worldtanjj
Copy link

干净整洁, 赞

@antonio-leonardo
Copy link

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