将逗号分隔列表连接到逗号分隔并用单引号括起来

时间:2011-08-03 23:44:42

标签: c# string c#-4.0 string-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));

现在s是'test's','test','test's more' 但我需要用2个单引号替换内部引号

像这样:'test''s','test','test''s more'

更新:我按照以下方式开始工作,但如果可能的话,我希望采用更清洁的方式。

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

6 个答案:

答案 0 :(得分:52)

这应该有效:

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

如果你真的希望将整个事情用单引号括起来:

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

答案 1 :(得分:22)

这可能比使用string.replace

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

答案 2 :(得分:3)

试试这个:

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

顺便说一句,“测试”中没有撇号 - 撇号aren't used for plurals

答案 3 :(得分:3)

这不是每个人的口味,但我喜欢为这些类型的任务创建帮助扩展,并将它们放入“实用程序”命名空间:

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

答案 4 :(得分:1)

您可以在构建字符串之前始终对引号进行编码。

答案 5 :(得分:-1)

I like a version without Replace:

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