I have a dynamic object that looks like this,
{ "2" : "foo", "5" : "bar", "8" : "foobar" }
How can I convert this to a dictionary
?
You can use a RouteValueDictionary to convert a C# object to a dictionary. See: RouteValueDictionary Class - MSDN. It converts object properties to key-value pairs. clever way of repurposing an existing class!
2 Answers. Show activity on this post. List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>() // Add list. Add(new KeyValuePair<string, string>("key", "value"));
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.
You can use a RouteValueDictionary
to convert a C# object to a dictionary. See: RouteValueDictionary Class - MSDN. It converts object
properties to key-value pairs.
Use it like this:
var toBeConverted = new { foo = 2, bar = 5, foobar = 8 }; var result = new RouteValueDictionary(toBeConverted);
You can fill the dictionary using reflection:
public Dictionary<String, Object> Dyn2Dict(dynamic dynObj) { var dictionary = new Dictionary<string, object>(); foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dynObj)) { object obj = propertyDescriptor.GetValue(dynObj); dictionary.Add(propertyDescriptor.Name, obj); } return dictionary; }
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