Turn Anonymous Types into IDictionary of values

My blog has moved. You can view this post at the following address: http://www.osherove.com/blog/2008/3/11/turn-anonymous-types-into-idictionary-of-values.html
Published Tuesday, March 11, 2008 5:22 PM by RoyOsherove

Comments

Tuesday, March 11, 2008 5:47 PM by Jacob

# re: Turn Anonymous Types into IDictionary of values

How does TypeDescriptor.GetProperties(...) differ from withProperties.GetType().GetProperties()?

Tuesday, March 11, 2008 5:52 PM by RoyOsherove

# re: Turn Anonymous Types into IDictionary of values

Jacob: I find it easier to work with, that's all.

Tuesday, March 11, 2008 6:46 PM by Andrew Davey

# re: Turn Anonymous Types into IDictionary of values

You could use this:

new Dictionary<string, string> { { "Name", "Roy" }, { "Country", "Israel" } };

A bit heavier on the syntax, but avoids the reflection.

Tuesday, March 11, 2008 7:36 PM by RoyOsherove

# re: Turn Anonymous Types into IDictionary of values

Andrew: Nice! I hadn't considered that option.

Tuesday, March 11, 2008 8:00 PM by Haacked

# re: Turn Anonymous Types into IDictionary of values

Roy, you can also do this now:

new RouteValueDictionary(new {key1="value1", key2="value2"};

RouteValueDictionary will be populated with the values from the anonymous type. Even though it is called "RouteValueDictionary" it inherits Dictionary<string, object> so is more generally useful assuming you are ok with case insensitivity.

Thursday, March 13, 2008 7:13 AM by Kent Boogaart

# re: Turn Anonymous Types into IDictionary of values

> Jacob: I find it easier to work with, that's all.

Plus it uses ICustomTypeDescriptor if you've implemented it. Which is obviously not the case here, but, you know, it's really kinda annoying when Type.GetProperties() is used where TypeDescriptor should be - like in NVelocity.

Thursday, March 20, 2008 5:11 AM by Joe Chung

# re: Turn Anonymous Types into IDictionary of values

People who don't like reflection will hate this version:

static public IDictionary<string, object> MakeDictionary(object o)

{

   Type type = o.GetType();

   return type.GetProperties()

       .Select(n => n.Name)

       .ToDictionary(k => k, k => type.GetProperty(k).GetValue(o, null));

}