I have the following object:
dynamic person = new {Id = 1, Name = "SpiderMan"};
I need to be able to iterate through the property names e.g. "Id"
, "Name"
.
I also need to be able to achieve this in the most efficient way therefore I chose to use FastMember however it's api does not allow me to iterate through the properties.
Any ideas?
[UPDATE]
Thanks to Marc I managed to achieve what I wanted using:
dynamic person = new { Id = 1, Name = "SpiderMan" };
MemberSet members = TypeAccessor.Create(person.GetType()).GetMembers();
foreach (Member item in members)
{
// do whatever
}
For the scenario you show, TypeAccessor.Create(obj.GetType())
and GetMember()
should work fine, since that type is fine for reflection.
In the more general case: that's a fair question - I honestly can't remember whether FastMember exposes this for true dynamic types, but one important consideration here is that by the very nature of dynamic objects, the set of properties may not even be enumerable - i.e. the code could respond to obj.Whatever
on the fly, without knowing about Whatever
in advance. For the object you actually have, however, simple reflection is your best bet. The scenario you show does not need dynamic
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With