Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Mar 25, 2014

@shaahink

This comment has been minimized.

Copy link

commented Nov 10, 2014

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

This comment has been minimized.

Copy link

commented Jun 24, 2016

Neat helper, very useful.
Thanks!

@worldtanjj

This comment has been minimized.

Copy link

commented Jul 27, 2018

干净整洁, 赞

@antonio-leonardo

This comment has been minimized.

Copy link

commented Oct 24, 2018

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
You can’t perform that action at this time.