Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET Core 6 : The best way to list a group of numbers in a string?

I have a string of numbers in the form of an object like this :

{ "7": "14", "8": "16", "10": "18", "19": "20" }

I want to put the numbers before ":" in a list and the numbers after it in a list, what is the best way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Working with Newtonsoft.Json, you can convert it to JObject and extract the keys and values via Properties() an Values().

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;

JObject jObj = JObject.Parse(input);
var keys = jObj.Properties()
    .Select(x => x.Name)
    .Where(x => int.TryParse(x, out _))
    .ToList();
var values = jObj.Values()
    .Select(x => x.ToString())
    .Where(x => int.TryParse(x, out _))
    .ToList();

From the Dictionary<string, string> instance, you can work with System.Linq to extract the Key and Value.

using System.Collections.Generic;
using System.Linq;

var dict = /* Dictionary<string, string> instance */;
        
var keys = dict.Select(x => x.Key)
    .Where(x => int.TryParse(x, out _))
    .ToList();
var values = dict.Select(x => x.Value)
    .Where(x => int.TryParse(x, out _))
    .ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading