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.

Wednesday, March 12, 2008 7:37 AM by Filini

# re: Turn Anonymous Types into IDictionary of values

I was going to link this post from Phil Haack's blog, on this subject

haacked.com/.../collection-initializers.aspx

but I see he beat me with his comment :-)

Anyway, on that post you get interesting comments on the possible syntaxes.

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.

# Dictionary To Anonymous Type &laquo; Jacob Carpenter&#8217;s Weblog

Pingback from  Dictionary To Anonymous Type &laquo; Jacob Carpenter&#8217;s Weblog

Thursday, March 13, 2008 3:13 PM by Jacob

# re: Turn Anonymous Types into IDictionary of values

And now you can round-trip back to an anonymous type instance: jacobcarpenter.wordpress.com/.../dictionary-to-anonymous-type

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));

}