I am writing a wrapper around some data library that executes sql statements and returns results.
The ExecuteQuery
command should ideally return an IEnumerable<T>
depending on what type of object the query results map to. The problem is that I cannot know what type this would be and therefore I would rather return a IEnumerable<dynamic>
type.
This is all good so far except that I want the dynamic objects properties to be the same as the columns being queried for but I cannot find anyway to assign this, I currently have all the column names in an array col[] e.g.
dynamic obj = new {} as dynamic;
for(int i = 0; i < col.Length; i++){
//say col[i] == 'id', I want obj.id = someValue
obj.? = someValue; ???
}
I hope this is clear. I hope it's not impossible!
p.s. I am writing this for WP7 so my options are severely limited, it might be good to keep this in mind.
Thanks for you help.
dynamic
is not applicable in your case. You usedynamic
when you know the property name at compile time but not the actual type that property will be defined on.If you know the property name only at runtime you will have to use ordinary reflection, something like this:
Please note that
dynamic obj = new {} as dynamic;
makes absolutely no sense. This will create an anonymous type without any properties. Assigning it to adynamic
variable doesn't change the fact that it doesn't have - and never will - any properties.If you are trying to dynamically add properties to an object, you might want to use
ExpandoObject
.Usage would be like this: