Search code examples
c#.netasp.net-core

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?


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();