Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c# - Join list of string to comma separated and enclosed in single quotes

List<string> test = new List<string>();
test.Add("test's");
test.Add("test");
test.Add("test's more");
string s = string.Format("'{0}'", string.Join("','", test));

now the s is 'test's','test','test's more' but I need to replace the inner quotes with 2 single quotes

like this: 'test''s','test','test''s more'

update: I got it to work as below, but I would prefer a cleaner way if possible.

string s = string.Format("`{0}`", string.Join("`,`", test)).Replace("'", "''").Replace("`", "'");
question from:https://stackoverflow.com/questions/6934629/join-list-of-string-to-comma-separated-and-enclosed-in-single-quotes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work:

List<string> test = new List<string>(); 
test.Add("test's"); 
test.Add("test"); 
test.Add("test's more");
string s = string.Join("','", test.Select(i => i.Replace("'", "''")));

And if you're really looking to enclose the whole thing in single quotes:

string s = string.Format("'{0}'", string.Join("','", test.Select(i => i.Replace("'", "''"))));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...