Consider the below code (which dynamically creates a dynamic SQL string)
Is there a way to further compact string.join, so it does replace(“‘”,”””) on all array members automagically ? (without writing a custom version)
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
You can use LINQ:
If you’re not using .Net 4, you’ll need to add
.ToArray()