Long time no post, here is something for fun, any object to a dictionary using an extension method!
Long time no post again :(, I will be getting back into it very soon if I can :).
I was a little bored tonight so I thought I would share my
extension method for converting an object to a dictionary,
mainly used to converting an anon type to a dictionary
for my url helper, i.e. new { id = 1, name = "bob" }
will be converted to a key value dictionary, the extension
method is as follows:
public static class Extensions {
///<summary>
/// Converts an object to a
dictionary based on its properties.
///</summary>
///<param
name="value"></param>
///<returns></returns>
public
static IDictionary<string, object> ToDictionary(this
object value) {
var dictionary = new
Dictionary<string, object>();
foreach (var prop in
value.GetType().GetProperties()) {
// For each property on the type get the name and value.
var val = prop.GetValue(value, null);
dictionary.Add(prop.Name, val);
}
return dictionary;
}
}
And to use. do this:
var item = new { id = 1, name = "22"};
var itemDict =
item.ToDictionary();
This will return a
dictionary from the type, but where this might also work is
if you have a class say Person with 2 properties ID and
Name, p.ToDictionary() will return a dictionary with Id and
Name in it from the Person class.
Not
terribly useful (I guess you could just use the
RouteValueDictionary from the System.Web.Routing library,
unless there is another way too), but it was helpful to me
:)
Cheers
Stefan