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

一笑奈何 提交于 2019-12-03 02:07:23

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

This may be easier than using string.replace

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

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.

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));

You can always encode quotes before you build your string.

I like a version without Replace:

using System.Linq;
(...)
string s = String.Join(", ", from l in MyList select String.Format("'{0}'", l));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!