2

Basically, I am trying to convert what appears to be an array of integer values stored in a string type.

[123,234,345,456] // example

Currently, I am doing the following to convert string to List<int> or an int[]:

var intList = "[123,234,345,456]".Replace("[","").Replace("]","").Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).Tolist();

Perform required operations (sort, add, remove) on the list and convert it back to a string:

string.Format("[{0}]", string.Join(",", intList));

But then this got me thinking. The data that I am working with looks like JSON. Surely there must a more direct way of converting the string into an array of integers?

I looked at using JArray.Parse(string) from Newtonsoft.Json.Linq but isn't that just adding an extra layer of complexity as now I am dealing with JArray<JToken> instead of standard int[].

If anyone has a neater solution that doesn't involve adding methods, extensions or libraries I would appreciate if you can share your knowledge.

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
iiminov
  • 969
  • 1
  • 15
  • 34
  • what is the exptected output? – Derviş Kayımbaşıoğlu Feb 25 '19 at 08:44
  • 5
    Possible duplicate of [Parsing JSON list to int array in c#](https://stackoverflow.com/questions/49341784/parsing-json-list-to-int-array-in-c-sharp) – kgzdev Feb 25 '19 at 08:45
  • You can use regex as well, – fhnaseer Feb 25 '19 at 08:46
  • If your input really is that simple you could use a regex, but that will soon get very cumbersome if your inout-format changes - e.g. if you have doubles instead of ints. – MakePeaceGreatAgain Feb 25 '19 at 08:46
  • `JsonDataContractSerializer` can do this: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.json.datacontractjsonserializer?view=netframework-4.7.2 – Ben Feb 25 '19 at 08:51
  • What do you mean by "extra layer of complexity"? are you concerned about performance? JSON seems to be more readable, it is fast as well. it's designed to work with strings anyway... – M.kazem Akhgary Feb 25 '19 at 08:52

2 Answers2

19

You are correct - JSON can do this for you:

using System;
using Newtonsoft.Json;

namespace Demo
{
    class Program
    {
        static void Main()
        {
            string test = "[123,234,345,456]";

            var result = JsonConvert.DeserializeObject<int[]>(test);

            // This prints "123, 234, 345, 456"

            Console.WriteLine(string.Join(", ", result));

            string andBackAgain = JsonConvert.SerializeObject(result);

            // This prints "[123,234,345,456]"

            Console.WriteLine(andBackAgain);
        }
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

If your intention is to parse numbers with double quotes then

    string input = @"[123,234,345,456]";
    string pattern = @"\d+";
    var result = Regex.Replace(input, pattern, "\"$&\"");
    result.Dump();
    //["123","234","345","456"]

or to parse whole object inside array braces

    string input = @"[123,234,345,456]";
    string pattern = @"(\d+\s*,?\s*)+";
    var result = Regex.Replace(input, pattern, "\"$&\"");
    result.Dump();
    //["123,234,345,456"]
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72