How to get first child of JObject without using foreach loop
Asked Answered
A

4

5

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).

Aeolus answered 16/1, 2015 at 19:15 Comment(0)
Y
6

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>();
Yacano answered 16/1, 2015 at 19:26 Comment(2)
I think it's best answer, because it uses native methods and does not require LINQ extensions. However, to get actual item it needs casting. JObject item = (obj["stats"].First as JProperty).Value as JObject You can update your answer if someone else needs it.Aeolus
@stil: A little cleaner would be obj["stats"].First.ToObject<JProperty>().Value if you know that it's a JProperty.Yacano
G
2

Since JObject implements IDicionary<string, JToken> you can use Linq extension methods.

 IDictionary<string, JToken> json = new JObject();
 var item = json.First();
Gull answered 16/1, 2015 at 19:26 Comment(0)
C
1

Wouldn't this work?

(json["stats"] as JObject).Select(x =>
      {
            // do something with the item;

            return x;
      }).FirstOrDefault();
Calabar answered 16/1, 2015 at 19:25 Comment(0)
I
0

You need to access to the "stats" by selecting token and access the first object in it.

var first = jo.SelectToken("stats").First;
Iatric answered 20/3 at 21:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.