I have a list as a single string like - "['2','4','5','1']" and length of this is 17 as each char is counted.
Now I want to parse it into list object like - ['2','4','5','1'] whose length will be 4 as the number of elements in a list.
How can I do this in C#?
Can it be done without doing basic string operations? If yes then how?
Without basing string operations
Your string value looks like valid JSON array.
using Newtonsoft.Json;
var list = JsonConvert.DeserializeObject<List<char>>("['2','4','5','1']");
// => ['2','4','5','1']
If you need output as integers set output type to be list of integers and JSON serializer will convert it to integers.
var list = JsonConvert.DeserializeObject<List<int>>("['2','4','5','1']");
// => [2, 4, 5, 1]
Converting to integers will handle negative values as well ;)
var list = JsonConvert.DeserializeObject<List<int>>("['-2','4','-5','1']");
// => [-2, 4, -5, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With