tags:

views:

667

answers:

3

I need to detect if an object was created anonymously like new{name=value,}

if it is an AnonymousType, it should add it's properties names/values into a

Dictionary<string,object>

This is what I hacked together myself:

var name="name";

var obj = new { name = new object(), };

var lookup = new Dictionary<string,object>();


if(obj.GetType().Name.StartsWith("<>f__AnonymousType"))
{
    foreach (var property in obj.GetType().GetProperties())
    {
        lookup[property.Name] = property.GetValue(obj, null);
    }
}
else
{
    lookup[name]=obj;
}

I was wondering if there is a better/faster way of detecting AnonymousTypes, or if there is a better/faster way to dump an object's properties names/values into a

Dictionary<string,object>
+1  A: 

Use the new collection object initializer syntax instead of an anonymous type:

var obj = new Dictionary<string, object>()
{
    { "Name", t.Name },
    { "Value", t.Value }
};
280Z28
+2  A: 

Detecting an anonymous type is a little hard; not-least it depends on the language! VB anon-types don't look the same as C# anon-types. I'd be dubious about logic that acts vary differently on anon-types. You might check for [CompilerGenerated], but note that it doesn't just mean "anonymous type" - there are others that do this.

Personally, I wouldn't distinguish in this scenario.

Marc Gravell
+7  A: 

To get all the properties of an object, with its values into a Dictionary, you can couple the power of Linq to Objects with Reflection.

You can use the Enumerable.ToDictionary method:

var dic = obj.GetType()
             .GetProperties()
             .ToDictionary(p => p.Name,  p=> p.GetValue(obj, null));

This will return you a Dictionary<string, object>.

CMS
The problem is if he can just use the dictionary in the first place, it would be enormously faster unless Linq is doing some crazy caching on that query, in which case it would "only" be measurably faster.
280Z28