C# - SelectTokens get multiple properties from a JSON structure

I have made a quite a few posts about SelectToken and SelectTokens by now. This post describes how to get two or more properties from a JSON structure without having to parse all of it to an object. We will reuse the JSON from my previous posts:

var jsonString = @"{
  ""quoteSummary"": {
    ""result"": [
      {
        ""assetProfile"": {
          ""address1"": ""One Apple Park Way"",
          ""city"": ""Cupertino"",
          ""state"": ""CA"",
          ""zip"": ""95014"",
          ""country"": ""United States"",
          ""phone"": ""408 996 1010"",
          ""website"": ""https://www.apple.com"",
          ""industry"": ""Consumer Electronics"",
          ""sector"": ""Technology""
        }
      }
    ]
  }
}";

With the above JSON we can use SelectTokens in combination with path using [] to get several properties:

var dictionary = new Dictionary<string, (string, string)>();

var data = (JObject)JsonConvert.DeserializeObject(jsonString);
var SelectStrings = data.SelectTokens(
    "quoteSummary.result[0].assetProfile['address1','city']").Values<string>();
//SelectStrings will contain a list of "One Apple Park Way" and "Cupertino"

Using the path "quoteSummary.result[0].assetProfile['address1','city'] we can get both the city and address in a list of strings.

However in most scenarios you would likely want to have the two properties as an object. For this you can use a simple Select statement:

var SelectStrings = data.SelectToken(
    "quoteSummary.result[0].assetProfile").Select(x => new
    {
        Address1 = x.Value<string>("address1"),
        City = x.Value<string>("city"),
    });

The above gets the values for address1 and city and returns them as properties of an anonymous object.

That is all

I hope you found this helpful, feel free to leave a comment down below!