Better way to converting string [123,234,…] to List<int> and back

  • A+

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 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.


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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: