进一步压缩弦.连接以取代撇号
本文关键字:取代 连接 压缩 进一步 | 更新日期: 2023-09-27 18:06:15
考虑下面的代码(它动态创建一个动态 SQL字符串)
是否有进一步压缩字符串的方法?连接,所以它会自动替换("'",")上的所有数组成员?(不编写自定义版本)
c#:[STAThread()]
public void Main()
{
string[] astrAllGroups = {
"Group A",
"Group B",
"D'Amato",
null
};
for (int i = 0; i < astrAllGroups.Length; ++i) {
if (!string.IsNullOrEmpty(astrAllGroups[i])) {
astrAllGroups[i] = astrAllGroups[i].Replace("'", "''");
}
}
string strDynSQL = "'" + string.Join("', '", astrAllGroups) + "'";
strDynSQL = strDynSQL.Replace("'", "''");
System.Windows.Forms.Clipboard.SetText(strDynSQL);
Console.WriteLine(strDynSQL);
Console.WriteLine(Environment.NewLine);
Console.WriteLine(" --- Press any key to continue --- ");
Console.ReadKey();
}
VB。净
<STAThread()> _
Sub Main()
Dim astrAllGroups As String() = {"Group A", "Group B", "D'Amato", Nothing}
For i As Integer = 0 To astrAllGroups.Length - 1 Step 1
If Not String.IsNullOrEmpty(astrAllGroups(i)) Then
astrAllGroups(i) = astrAllGroups(i).Replace("'", "''")
End If
Next
Dim strDynSQL As String = "'" + String.Join("', '", astrAllGroups) + "'"
strDynSQL = strDynSQL.Replace("'", "''")
System.Windows.Forms.Clipboard.SetText(strDynSQL)
Console.WriteLine(strDynSQL)
Console.WriteLine(Environment.NewLine)
Console.WriteLine(" --- Press any key to continue --- ")
Console.ReadKey()
End Sub
您可以使用LINQ:
string strDynSQL = "'" + string.Join("', '",
astrAllGroups.Select(s => s.Replace("'", "''"))
) + "'";
如果你不使用。net 4,你需要添加.ToArray()
只要使用。net 3或更新版本,就可以使用LINQ:
var strDynSql =
"'"
+ String.Join("', '",
astrAllGroups.Select(s => s.Replace("'","''")).ToArray())
+ "'";