Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to List - c#

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?

like image 514
Tanmay Bairagi Avatar asked Jul 05 '26 00:07

Tanmay Bairagi


1 Answers

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]
like image 62
Fabio Avatar answered Jul 06 '26 19:07

Fabio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!