C# String Formatting – Join List to Comma-Separated String Enclosed in Single Quotes

c#-4.0c++stringstring-formatting

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("`", "'");

Best Answer

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("'", "''"))));