2

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.

webworm
  • 10,587
  • 33
  • 120
  • 217
  • I think your first `Select` is going to remove everything except token "id", which means there is "name" to use in the `Where` - what is it there for? – NetMage Jul 13 '18 at 20:04
  • I tried putting the `Where` first but got the same results. `var groupId = parsedJson["value"].Where(y => y.SelectToken("name").ToString() == groupName).Select(x => x.SelectToken("id"));`. I want to grab the `id` property of the element in the `value` array where the `name` property is `Tissue Preps` – webworm Jul 13 '18 at 20:27
  • What type do you want `GroupId` to be? What if more than one member of "value" has the name of "Tissue Preps"? The `Select` definitely needs to go to the end. Are you sure that error is on this line, I don't see how? – NetMage Jul 13 '18 at 20:41
  • `groupId` will be a `string`. There will not be any cases where more than one has the same `name` value. Basicaly I am trying to find the identifier based on the `name` – webworm Jul 13 '18 at 20:42
  • The return type from `Select` is? I believe you want `First` instead of `Where`. – NetMage Jul 13 '18 at 20:43

1 Answers1

1

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();
NetMage
  • 26,163
  • 3
  • 34
  • 55