Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of key value pairs to a dynamic object

Basically I'm trying to convert from:

keys[3] = {"id", "name", "comment"}
values[3] = {"1", "Ackerman", "superuser"}

to:

new { id: "1", name: "Ackerman", comment: "superuser"}

How can I do this?

like image 660
hurtchin Avatar asked Jun 25 '14 14:06

hurtchin


People also ask

How do you add a key-value pair in an object dynamically?

Answer: Use Dot Notation or Square Bracket You can simply use the dot notation ( . ) to add a key/value pair or a property to a JavaScript object.

How do you convert a key-value pair to a list?

ToList() Method. A simple solution is to use ToList() method to create a List<KeyValuePair> from a Dictionary<TKey,TValue> . It is available in LINQ and you need to add System. Linq namespace.

How do you create a dynamic object?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.


1 Answers

I think wat you want is an Expando object which allows to add dinamically properties:

keys[3] = {"id", "name", "comment"}
values[3] = {1, "Ackerman", "superuser"}

dynamic item = new ExpandoObject();
var dItem = item as IDictionary<String, object>;

for(int buc = 0; buc < keys.Length; buc++)
    dItem.Add(keys[buc], values[buc]);

After that you can call your object as you will do with any other:

var id = item.id;
var comment = item.comment;
item.name = "new name";
like image 178
Gusman Avatar answered Oct 04 '22 15:10

Gusman