48
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("`", "'");
Eric J.
  • 147,927
  • 63
  • 340
  • 553
coder
  • 4,121
  • 14
  • 53
  • 88

8 Answers8

77

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("'", "''"))));
Jay Riggs
  • 53,046
  • 9
  • 139
  • 151
34

This may be easier than using string.replace

string s = "'" + String.Join("','", test) + "'";
Scott
  • 21,211
  • 8
  • 65
  • 72
CraigH
  • 349
  • 3
  • 2
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.

Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
  • :) You are right. I made up some test list, I didn't really mean to say test's. Just some data with apostrophe is all I wanted. – coder Aug 04 '11 at 00:15
3

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));
davecoulter
  • 1,806
  • 13
  • 15
  • this one is cool, I prefer the above one is because I need it in just one place to use it. However I just learned how to create extensions. Thanks. – coder Aug 04 '11 at 00:11
  • @gangt No problem! The first time I learned extensions I thought it was pretty awesome too. – davecoulter Aug 04 '11 at 00:12
3
string s = string.Join(
    ',', itemsList.Select(
        i => $"'{i}'"));

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

tripleee
  • 175,061
  • 34
  • 275
  • 318
Som Das
  • 31
  • 1
0

You can always encode quotes before you build your string.

ika
  • 1,889
  • 2
  • 12
  • 9
0
string.Join(",", listofstring.Select(x=> $"'{x}'"))
Nissanna
  • 1
  • 3
-1

I like a version without Replace:

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