PhatLee
PhatLee

Reputation: 37

Convert a line of Data into a string list

I have a string which looks like

string data = "\"111\",67215,\"JOHN A DOE\",\"123456789\",\"1212\",\"FP3S\""

I need to split each of them and store it in database table in their individual column. I tried to split like

string[] separator = new string[]{“,”};
List<string>splitdata = data.split(separator, StringSplitOptions.None).ToList();

It will split in 6 columns but give me results like:

“\”100|””
“67215”
“\”JOHN A DOE\”” … and so on.

I tried again just using double quotes (“”). But it will only split it in 3 columns

“\”111\,67215,\”JOHN”
“A”
“DOE\”,\",\"123456789\",\"1212\",\"FP3S\""

What I want is like

"111","67215","JOHN A DOE","123456789","1212","FP3S"

How do I format it so that I get data in above format?

Upvotes: 1

Views: 151

Answers (3)

masehhat
masehhat

Reputation: 690

Use Replace method to remove \" , After that you could use split to make your collection.

string[] items = data.Replace("\"", "").Split(',');

Upvotes: 0

Amir Molaei
Amir Molaei

Reputation: 3820

Try this (Demo):

string data = "\"111\",67215,\"JOHN A DOE\",\"123456789\",\"1212\",\"FP3S\"";
List<string> splitdata = data.Split(',').Select(s => s.Replace("\"", "")).ToList();

Upvotes: 2

ingvar
ingvar

Reputation: 4377

var data = "\"111\",67215,\"JOHN A DOE\",\"123456789\",\"1212\",\"FP3S\"";
var splittedData = data.Split(',').Select(s => s.Trim('\"')).ToList();

This code splits string by ,, and removes " from start and end of each string.

Upvotes: 0

Related Questions