简体   繁体   中英

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?

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]

Try to Split by , and then use Regex to get only digits:

var str = "['2','4','5','1']".Split(new char[] {',' })
    .Select(s => Regex.Match(s, @"\d+").Value);

Or thanks to @Fildor :

var str = Regex.Matches("['2','4','5','1']", @"\d+").Cast<Match>()
    .Select(s=> s.Value);

You can try regular expressions and Linq in order to Match all the integers and turn them ( ToList() ) into List<int> :

using System.Linq;
using System.Text.RegularExpressions;

...

string str = "['2','4','5','1']";

var result = Regex
  .Matches(str, @"\-?[0-9]+")              // \-? for negative numbers
  .Cast<Match>()
  .Select(match => int.Parse(match.Value)) // int.Parse if you want int, not string
  .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM