Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

c# - 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 ?

question from:https://stackoverflow.com/questions/65847980/how-to-check-if-the-value-of-a-key-is-equal-through-out-the-list-of-json-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...