Search code examples
c#linqsystem.text.jsonjsonnode

How does one iterate a JsonArray with LINQ?


I have JSON:

{
    "dimensions": [
        {
            "name": "dim1"
        },
        {
             "name": "dim2"
        },
        {
             "name": "dim3"
        }
    ]
}

Loaded into JsonObject

JsonObject root = JsonNode.Parse(jsonString)?.AsObject();

And I wish to iterate a JsonArray with LINQ

var list =  root["dimensions"].GetEnumerator().Select(p => p["name"].GetValue).ToArray();

But get error

CS1061: 'IEnumerator<JsonNode?>' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'IEnumerator<JsonNode?>' could be found (are you missing a using directive or an assembly reference?)

I find little when googling on JsonNode and LINQ. Perhaps not yet supported?


Solution

  • Use AsArray on node returned by jsonNode["dimensions"]:

    var list = jsonNode["dimensions"].AsArray()
        .Select(node => node["name"].AsValue().GetValue<string>()) // or node["name"].ToString()
        .ToArray();