Search code examples
c#jsonmin

Is there a simple way to find out lowest value from JSON without doing de-serialization?


I have below JSON output from API. I want to find out lowest value among all elements.

JSON data:

{
  "prices": [   
    {
      "frequency": "daily",
      "date": "2020-05-05",
      "intraperiod": false,
      "open": 295.06,
      "high": 301.0,
      "low": 294.46,
      "close": 297.56
    },
    {
      "frequency": "daily",
      "date": "2020-05-04",
      "intraperiod": false,
      "open": 289.17,
      "high": 293.69,
      "low": 112.1,
      "close": 293.16
    },
    {
      "frequency": "daily",
      "date": "2020-05-01",
      "intraperiod": false,
      "open": 286.25,
      "high": 299.0,
      "low": 222,
      "close": 289.07
    }
  ]
}

I want to compare all values among JSON element and display lowest value = "low": 112.1 and its own high value. "high": 293.69,

I tried like below using jQuery, but how can I do it in C#?

function get(arr, prop) {
    var min;
    for (var i=0 ; i<arr.length ; i++) {
        if (min== null || parseInt(arr[i][prop]) > parseInt(min[prop]))
            min= arr[i];
    }
    return min;
}

var min = get(arr, "low");
console.log(min.high);

Solution

  • You may use Newtonsoft.Json.Linq for that, parse your JSON to JObject, then get all properties with low name, find the property with lowest value and get the high value at the same level

    var json = JObject.Parse(jsonString);
    
    var properties = json.DescendantsAndSelf()
        .OfType<JProperty>()
        .Where(p => p.Name == "low");
    
     var lowProperty = properties
         .Aggregate((p1, p2) => p1.Value.Value<double>() < p2.Value.Value<double>() ? p1 : p2);
    
    var highProperty = (lowProperty?.Parent as JObject)?.Property("high");
    Console.WriteLine(lowProperty);
    Console.WriteLine(highProperty);
    

    It gives you

    "low": 112.1
    "high": 293.69