-1

Help me to create single object with dynamic properties.

For example: Suppose we are getting the following object from database,

var obj=[ 
{"name":"John", "age":35}, 
{"name":"Greesham", "age":37},
{"name":"Raman","age":42},
{"name":"Krish", "age":30}];

Now we want to create an object with above object values as keys/properties in c# class.

Expected Result:

var obj2=new{ John=35, Greesham=37, Raman=42, Krish=30 };

[Note: Here i can use IDictionary but i want only one object, to pass templater plugin to print in word document]

Thanks in advance.

Shabbir G
  • 1
  • 2

1 Answers1

0

try this

Dictionary<string, int> obj2 = JArray.Parse(obj)
                                   .ToDictionary(
                                   ja => (string)ja["name"],
                                   ja => (int) ja["age"]
                                   );

but if you want complitely independent from property names

Dictionary<string, object> obj2 = JArray.Parse(obj)
                                 .ToDictionary(
                                 ja => (string)((JObject)ja).Properties().ToArray()[0].Value,
                                 ja => (object) ((JObject)ja).Properties().ToArray()[1].Value
                                 );
Serge
  • 40,935
  • 4
  • 18
  • 45