0

I have a json object as the following:

{
    "search-results": {
        "results-count": "2"
        "entry": [
            {
                "id": "0",
                "count": "10",
            },
            {
                "id": "1",
                "count": "22",
            }
        ]
    }
}

I would like to get the sum of counts; 32 in this example. I am looking into doing this using LINQ, but any more "readable" alternative would be appreciate.

3
  • Just like a simple linq query like searchresults.entry.Sum(i => i.count); ? Commented Sep 15, 2019 at 18:52
  • cannot get anything like that working, any code example? Commented Sep 15, 2019 at 18:58
  • What have you tried so far? Please add your LINQ as well to question. Commented Sep 15, 2019 at 19:00

2 Answers 2

1

Try this:

var json = @"{
        'search-results': {
                    'results-count': '2',
                    'entry': [
                    {
                        'id': 0,
                        'count': 10,
                    },
                    {
                        'id': 1,
                        'count': 22,
                    }
            ]
        }
    }";


JObject searchResult = JObject.Parse(json);
int sum = (from entry in searchResult["search-results"]["entry"]
            select (int)entry["count"]).Sum();
Sign up to request clarification or add additional context in comments.

Comments

1

You could do it with Linq. For example,

var jobject = JObject.Parse(jsonString);
var result = jobject["search-results"]["entry"].Sum(x=>Convert.ToInt32(x["count"]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.