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


Solution 1:[1]

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

Solution 2:[2]

This may be easier than using string.replace

string s = "'" + String.Join("','", test) + "'";

Solution 3:[3]

Try this:

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

By the way, there's no apostrophe in "tests" - apostrophes aren't used for plurals.

Solution 4:[4]

It isn't to everyone's taste, but I like to create helper extensions for these kinds of tasks, and put them into a "utility" namespace:

public static class ListExtensions
{
   public static void AddDoubleQuoted(this List<string> list, string input)
   {
     input = input.Replace("'", "''");
     list.Add(input);
   }
}

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

Solution 5:[5]

You can always encode quotes before you build your string.

Solution 6:[6]

string s = string.Join(',', itemsList.Select(i => $"'{i}'"));

Using string interpolation. String.Replace is not required here.

Solution 7:[7]

I like a version without Replace:

using System.Linq;
(...)
string s = String.Join(", ", from l in MyList select String.Format("'{0}'", l));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Scott
Solution 3 Simon M?Kenzie
Solution 4 davecoulter
Solution 5 ika
Solution 6 Som Das
Solution 7 Starli0n