简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM