考虑以下代码(动态创建动态 SQL字符串)
有没有办法进一步压缩string.join,所以它会自动替换(“'”,“''”)所有数组成员? (不编写自定义版本)
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.NET
<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
答案 0 :(得分:1)
您可以使用LINQ:
string strDynSQL = "'" + string.Join("', '",
astrAllGroups.Select(s => s.Replace("'", "''"))
) + "'";
如果您不使用.Net 4,则需要添加.ToArray()
答案 1 :(得分:0)
只要您使用的是.NET 3或更高版本,就可以使用LINQ:
var strDynSql =
"'"
+ String.Join("', '",
astrAllGroups.Select(s => s.Replace("'","''")).ToArray())
+ "'";