我想将数组元素连接成字符串..
我有这个代码
Dim qry(3) As String
Dim text As String
If (TextBox1.Text <> String.Empty) Then
qry(0) = "f_name = '" + TextBox1.Text + "'"
End If
If (TextBox2.Text <> String.Empty) Then
qry(1) = "m_name = '" + TextBox2.Text + "'"
End If
If (TextBox3.Text <> String.Empty) Then
qry(2) = "l_name = '" + TextBox3.Text + "'"
End If
text = String.Join(" AND ", qry)
MsgBox(text)
像这样连接数组
f_name =&#39; XYZ&#39; AND m_name =&#39; PQR&#39; AND l_name =&#39; ABC&#39;和
但我想要像这样的字符串
f_name =&#39; XYZ&#39; AND m_name =&#39; PQR&#39; AND l_name =&#39; ABC&#39;
答案 0 :(得分:0)
而不是使用string.Join()
尝试在自己的循环中构建你的qry:
Dim qryTxt As string = string.Empty
For i As integer = 0 To qry.GetUpperBound(0)
If qryTxt = string.Empty() Then
qryTxt = qry(i)
Else
qryTxt = qryTxt + " AND " + qry(i)
End If
Next
答案 1 :(得分:0)
你应该避免与+和&amp;串联。 使用System.Text.StringBuilder。它的速度要快得多(我曾经用一个程序来在查询指令中导出数据库并且连接它花了几分钟,StringBuilder不到5秒)。 所以你的代码应该是:
Dim sb As new system.Text.StringBuilder
If (TextBox1.Text <> String.Empty) Then
sb.Append("f_name = '")
sb.Append(TextBox1.Text)
sb.Append("'")
End If
If (TextBox2.Text <> String.Empty) Then
if sb.Length>0 then sb.Append(" AND ")
sb.Append("m_name = '")
sb.Append(TextBox2.Text)
sb.Append("'")
End If
If (TextBox3.Text <> String.Empty) Then
if sb.Length>0 then sb.Append(" AND ")
sb.Append("l_name = '")
sb.Append(TextBox3.Text)
sb.Append("'")
End If
MsgBox(sb.ToString)
假设您不需要其他地方的值数组。处理两次是不合理的。如果你需要数组,你可以使用String.Concat(st1,st2,st3 ......)它也提供了良好的性能。而不是循环
答案 2 :(得分:0)
只需使用通用List而不是静态数组:
Dim arrFilters As List<String>
Dim text As String
If (TextBox1.Text <> String.Empty) Then
arrFilters.Add("f_name = '" + TextBox1.Text + "'")
End If
If (TextBox2.Text <> String.Empty) Then
arrFilters.Add("m_name = '" + TextBox2.Text + "'")
End If
If (TextBox3.Text <> String.Empty) Then
arrFilters.Add("l_name = '" + TextBox3.Text + "'")
End If
text = String.Join(" AND ", arrFilters)