Get properties of a Dynamic Type
If someone is still struggling with this (as I did), this might be useful.
Let's say data
is the dynamic you want to list all properties from:
This worked for me
using System.ComponentModel;
...
dynamic data = new {
value1 = 12,
value2 = "asdasd",
value3 = 98,
value4 = "pgiwfj",
};
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(data))
{
Console.WriteLine("PROP: " + prop.Name);
}
...
Then it would output:
- PROP: value1
- PROP: value2
- PROP: value3
- PROP: value4
Source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/251e4f3d-ce90-444a-af20-36bc11864eca/how-to-get-list-of-properties-of-dynamic-object-?forum=csharpgeneral
You can use reflection to get the properties out and convert it to a dictionary:
dynamic v = new { A = "a" };
Dictionary<string, object> values = ((object)v)
.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(v));