Search code examples
c#jsonlistdata-structuresjson.net

How to check if the value of a key is equal through out the list of JSON Object


I am trying input some validation in C#. I have a LIST of JSON Object, and I want to add a validation that will check for a value of certain key and make sure they are all same in all the JSON object in the array.

LIST -

subtitles = [{ frameRate : '25', dropFrame: False}, { frameRate : '25', dropFrame: False}, { frameRate : '25', dropFrame: False}, { frameRate : '23', dropFrame: False}]

I want to add validation that will loop through every object and make sure that the value of the key frameRate is same through the array.

This is what i tried to do - I created a aempty list and then tried to push all the frameRates and then looped through it and compared the value with previous one.

List<string> subtitleSegmentsFrameRates = new List<string>();

            foreach (var subtitle in segmentSubtitles) 
            {
                subtitleSegmentsFrameRates.Add(subtitle.frameRate);
                    
            }

            for (int i = 0; i < subtitleSegmentsFrameRates.Count; i++) {
                if (i != 0) {
                    if (subtitleSegmentsFrameRates[i] != subtitleSegmentsFrameRates[i - 1]) {
                        throw new CustomException("Frame Rates arocss segments do not match.");
                    }
                }
            }

Is there a better way to do this ?


Solution

  • You can compare all the items against the first one after parsing input to JArray and linq All method

    var jArray = JArray.Parse(subtitles);
    bool allSame = jArray.All(j => j["frameRate"].Value<string>() == jArray[0]["frameRate"].Value<string>());
    

    j["frameRate"] is type of JToken that's why to convert to string .Value<string>() is invoked over it.

    Another way which is also suggested by @John:

    bool same = jArray.Select(j => j["frameRate"].Value<string>()).Distinct().Count() == 1
    

    Check this fiddle - https://dotnetfiddle.net/5xOJB5