Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting dynamic type to dictionary C#

I have a dynamic object that looks like this,

 {     "2" : "foo",     "5" : "bar",     "8" : "foobar"  } 

How can I convert this to a dictionary?

like image 917
Kristian Nissen Avatar asked Feb 27 '14 09:02

Kristian Nissen


People also ask

How to convert dynamic object into dictionary c#?

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!

How to add values dynamically to dictionary in c#?

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"));

What is dynamic type C#?

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.


2 Answers

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); 
like image 94
annemartijn Avatar answered Sep 18 '22 19:09

annemartijn


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; } 
like image 41
ema Avatar answered Sep 20 '22 19:09

ema