Search code examples
linqlinq-to-json

LINQ to JSON - Select array object element where specific property matches


MY LINQ-Fu skills pretty bad and after looking at JSON.NET examples I am still having trouble figuring out how to select that data I am after. I have a blob of JSON as follows ...

{
    "@odata.context": "http://wabi-us-north-central-b-redirect.analysis.windows.net/v1.0/myorg/$metadata#groups",
    "@odata.count": 2,
    "value": [
        {
            "id": "z48856e6-f385-4c89-a4b8-33c24hsr5c",
            "isReadOnly": false,
            "isOnDedicatedCapacity": false,
            "name": "Blood Values"
        },
        {
            "id": "k95d7cfe-c2a5-41f9-804w-e1b7ab31g31k",
            "isReadOnly": false,
            "isOnDedicatedCapacity": false,
            "name": "Tissue Preps"
        }
    ]
}

I am trying to write a LINQ to JSON expression that will allow me to select the value of the id element where the name value is equal to `Tissue Preps'.

var parsedJson = JObject.Parse(webResponse.Response);
var datasetId = parsedJson["value"].Select(i => i.SelectToken("id")).Where(n => n.SelectToken("name").ToString() == "Tissue Preps");

Above is the LINQ expression I tried but I end up getting a Object reference not set to an instance of an object. error. I would like to avoid having to write a class to represent the JSON so it can be deserialized.


Solution

  • Since you expect a single answer and not an IEnumerable, you need to use First:

    var parsedJson = JObject.Parse(webResponse.Response);
    var datasetId = parsedJson["value"].First(n => n.SelectToken("name").ToString() == "Tissue Preps")
                                       .SelectToken("id")
                                       .ToString();