Search code examples
c#jsonjson.net

How to get first child of JObject without using foreach loop


I need to get the first child of JObject. This is how I temporarily solved it with foreach loop breaking after first iteration.

foreach (KeyValuePair<string, JToken> item in (JObject)json["stats"])
{
    // doing something with item
    break;
}

I wonder if there is shorter solution, like json["stats"][0] (however it doesn't work this way).


Solution

  • There are probably a few ways, but here's one:

    JToken prop = obj["stats"].First;
    

    If you know it's a JProperty:

    JProperty prop = obj["stats"].First.ToObject<JProperty>();