我试图建立将在SELECT语句的子句中使用的列表。要求是让用户输入逗号分隔的描述列表。每个描述都可以包含空格,因此在用逗号分隔以在每个描述周围添加单引号前,我无法删除空格。我想在单引号后删除所有空格,因为没有描述将以空格开始。在VB.NET中做这件事的最好方法是什么?正则表达式或字符串函数?以下是我迄今为止:什么是字符串中的某个字符后,删除空白的最佳途径?
Partial Class Test
Inherits System.Web.UI.Page
Protected Sub cmdGetParts_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdGetParts.Click
Dim sDescriptionList As String = ""
BuildList(sDescriptionList)
RemoveSpacesFromList(sDescriptionList)
FillGrid(sDescriptionList)
End Sub
'Build descriptions List based on txtDescriptionList.Text
Private Sub BuildList(ByRef sDescriptionList As String)
Dim sDescriptionArray As String()
sDescriptionArray = txtDescriptionList.Text.Trim.Split(","c)
Dim iStringCount As Integer = 0
For Each description In sDescriptionArray
If iStringCount > 0 Then
sDescriptionList = sDescriptionList & ","
End If
sDescriptionList = sDescriptionList & "'" & description & "'"
iStringCount = iStringCount + 1
Next
End Sub
**'This procedure removes unwanted spaces from description list
Private Sub RemoveSpacesFromList(ByRef sList As String)
sList = sList.Replace("' ", "'")
End Sub**
'This procedure fills the grid with data for descriptions passed in
Private Sub FillGrid(ByVal sDescriptionList As String)
Dim bo As New boPart
Dim dtParts As Data.DataTable
dtParts = bo.GetPartByDescriptionList(sDescriptionList)
GridView1.DataSource = dtParts
GridView1.DataBind()
End Sub
End Class
编辑:回顾这段代码后,我想我或许可以只需将 description.Trim内对于BuildList过程的每个循环。
使用STR = STR:在一个循环中尺度非常糟糕的项目,如每个添加的项目都会增加内存使用量。对于每10个项目,内存使用量大约是1000倍。一个StringBuilder是建立一个循环的字符串的首选,但在我的建议下面,你根本不需要循环。 – Guffa 2009-04-17 14:50:36