I have a JObject like this:
JObject grid =
            new JObject(
            new JProperty("myprop", "value 1"),
            new JProperty("name", 
                new JArray(
                                new JObject(
                        new JProperty("myprop2", "value 2")
                    )
                )
            )
        )
Nothing wrong with that.
But, I have an object that I want to iterate over, and add them to my JObject, but how to do that?
Like this? (which is not valid, I know)
JObject grid =
            new JObject(
            new JProperty("myprop", "value 1"),
            new JProperty("name", 
                new JArray(
                                new JObject(
                        new JProperty("myprop2", "value 2"),
                        foreach(var value in myObject) {
                            new JObject(
                                new JProperty(value.Name, value.Value)
                            )   
                        }
                    )
                )
            )
        )
How can I do this?
You can also add properties to an existing JObject:
var obj = new JObject();
Console.WriteLine(obj.ToString()); // {}
obj.Add("key", "value");
Console.WriteLine(obj.ToString()); // {"key": "value"}
If you know your array items in advance why not create them first?
var myprop2Items = new List<JObject>();
foreach(var value in myObject) {
                            myprop2Items.Add(new JObject(
                                new JProperty(value.Name, value.Value)
                            ));
} 
JObject grid =
            new JObject(
            new JProperty("myprop", "value 1"),
            new JProperty("name", 
                new JArray(
                                new JObject(
                        new JProperty("myprop2", "value 2"),
                        myprop2Items
                        )
                    )
                )
            )
        )
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