Is there a way to access the properties of a dynamic object by index?
List<dynamic> list = _dataStagingManager.GetStatusList(consoleSearch);
foreach (var row in list)
{
Console.WriteLine(row[0]);
Console.WriteLine(row[1]);
}
In this example, the property name of row[0] is different depending on the results from a stored procedure column alias.
Unfortunately, no. Unlike runtime objects (which have an iterable collection of their members that can easily be reflected/queried against) dynamic objects, by default, have no such collection. They can be implemented in any way that allows their members to be accessed by name. There is no idea of indices with dynamic objects, provided you don't choose to implement them yourself.
If you wanted to, you could override the TryGetIndex
method on your dynamic type to provide indexing support.
In general, that's not possible. For example, you could create a dynamic object that has every possible property:
class AnythingGoes : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = binder.Name;
return true;
}
}
There is a chance you will be able to get the list of properties. If the dynamic object is actually normal object (one that does not implement IDynamicMetaObjectProvider
), normal reflection will work fine.
If the object actually is dynamic (implements IDynamicMetaObjectProvider
), you could try calling GetDynamicMemberNames()
on the DynamicMetaObject
returned from GetMetaObject()
. But, as the example above shows, this is not guaranteed to work.
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