Here is an example, but if you drop the comment or refine your post, it can be more visual. Given this class:
class Foo { public Foo(int bar, string baz) { Bar = bar; Baz = baz; } public int Bar { get; set; } public string Baz { get; set; } }
You can create a dictionary of its properties and values โโof a public instance as follows:
var valuesByProperty = foo.GetType(). GetProperties(BindingFlags.Public | BindingFlags.Instance). ToDictionary(p => p, p => p.GetValue(foo));
If you want to include more or different results, specify a different BindingFlags in the GetProperties method. If this does not answer your question, leave a comment.
Alternatively, assuming you are working with a dynamic object and anonymous types, the approach is similar. The following example obviously does not require the Foo class.
dynamic foo = new {Bar = 42, Baz = "baz"}; Type fooType = foo.GetType(); var valuesByProperty = fooType. GetProperties(BindingFlags.Public | BindingFlags.Instance). ToDictionary(p => p, p => p.GetValue(foo));
source share