stil
stil

Reputation: 5566

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

Upvotes: 5

Views: 18496

Answers (4)

esenkaya
esenkaya

Reputation: 418

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

var first = jo.SelectToken("stats").First;

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

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>();

Upvotes: 6

hansmaad
hansmaad

Reputation: 18905

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

 IDictionary<string, JToken> json = new JObject();
 var item = json.First();

Upvotes: 2

Tejs
Tejs

Reputation: 41256

Wouldn't this work?

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

            return x;
      }).FirstOrDefault();

Upvotes: 1

Related Questions