C# - Convert a string of Key value pair separated by '=' to Dictionary C# - Convert a string of Key value pair separated by '=' to Dictionary arrays arrays

C# - Convert a string of Key value pair separated by '=' to Dictionary


You can use Linq with Trim, Split, Select, ToDictionary

var result = json.Trim('{', '}')                 .Split(',')                 .Select(x => x.Split('='))                 .ToDictionary(x => x[0], x => int.Parse(x[1]));Console.WriteLine(string.Join("\r\n", result.Select(x => x.Key + " : " + x.Value)));

Full Demo Here

And just because i'm bored

Benchmarks

Mode             : Release (64Bit)Test Framework   : .NET Framework 4.7.1Operating System : Microsoft Windows 10 ProVersion          : 10.0.17134CPU Name         : Intel(R) Core(TM) i7-3770K CPU @ 3.50GHzDescription      : Intel64 Family 6 Model 58 Stepping 9Cores (Threads)  : 4 (8)      : Architecture  : x64Clock Speed      : 3901 MHz   : Bus Speed     : 100 MHzL2Cache          : 1 MB       : L3Cache       : 8 MBBenchmarks Runs : Inputs (1) * Scales (3) * Benchmarks (3) * Runs (100) = 900

Results

--- Random Set ----------------------------------------------------------------------| Value       |   Average |   Fastest |      Cycles |    Garbage | Test |      Gain |--- Scale 100 -------------------------------------------------------- Time 0.229 ---| Split       |  0.058 ms |  0.043 ms |     207,064 |  48.000 KB | Base |    0.00 % || JsonReplace |  0.077 ms |  0.064 ms |     273,556 |  24.000 KB | Pass |  -32.38 % || Regex       |  0.270 ms |  0.235 ms |     950,504 |  80.000 KB | Pass | -364.87 % |--- Scale 1,000 ------------------------------------------------------ Time 0.633 ---| Split       |  0.490 ms |  0.446 ms |   1,718,180 | 495.102 KB | Base |    0.00 % || JsonReplace |  0.671 ms |  0.596 ms |   2,352,043 | 195.078 KB | Pass |  -36.86 % || Regex       |  2.544 ms |  2.293 ms |   8,897,994 | 731.125 KB | Pass | -419.00 % |--- Scale 10,000 ----------------------------------------------------- Time 5.005 ---| Split       |  5.247 ms |  4.673 ms |  18,363,748 |   4.843 MB | Base |    0.00 % || JsonReplace |  6.782 ms |  5.488 ms |  23,721,593 |   1.829 MB | Pass |  -29.25 % || Regex       | 31.840 ms | 27.008 ms | 111,277,134 |   6.637 MB | Pass | -506.80 % |-------------------------------------------------------------------------------------

Data

private string GenerateData(int scale){   var ary = Enumerable.Range(0, scale)                       .Select(x => $"X{x}={Rand.Next()}")                       .ToList();   return $"{{{string.Join(",", ary)}}}";}

Split

public class Split : Benchmark<string, Dictionary<string,int>>{   protected override Dictionary<string,int> InternalRun()   {      return Input.Trim('{', '}')                       .Split(',')                       .Select(x => x.Split('='))                       .ToDictionary(x => x[0], x => int.Parse(x[1]));   }}

Regex

Credited to emsimpson92 using Cast

public class Regex : Benchmark<string, Dictionary<string,int>>{   protected override Dictionary<string,int> InternalRun()   {      var regex = new System.Text.RegularExpressions.Regex("(?<key>[^,]+)=(?<value>[^,]+)");      var matchCollection = regex.Matches(Input.Trim('{', '}'));      return matchCollection.Cast<Match>()                     .ToDictionary(                         x => x.Groups["key"].Value,                         x => int.Parse(x.Groups["value"].Value));   }}

JsonReplace

Credited to Hanzalah Adalan Modified to work with string.replace

public unsafe class JsonReplace : Benchmark<string, Dictionary<string,int>>{   protected override Dictionary<string,int> InternalRun()   {     return JsonConvert.DeserializeObject<Dictionary<string,int>>(Input.Replace("=", ":"));   }}

Additional Resources

String.Trim Method

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.

String.Split Method (String[], StringSplitOptions)

Splits a string into substrings based on the strings in an array. You can specify whether the substrings include empty array elements.

Enumerable.Select Method (IEnumerable, Func)

Projects each element of a sequence into a new form.

Enumerable.ToDictionary Method (IEnumerable, Func)

Creates a Dictionary from an IEnumerable according to a specified key selector function.


This can be done with Regex The following pattern will capture keys and values in 2 separate groups (?<key>[^,]+)=(?<value>[^,]+)

Demo

Once you have your MatchCollection, run a foreach loop through it, and add each element to a dictionary.


Var myAwesomeDictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(_yourJsonStringHere);