【发布时间】:2009-04-17 14:24:43
【问题描述】:
我正在尝试构建一个列表,该列表将用作 select 语句的 in 子句。要求是让用户输入以逗号分隔的描述列表。每个描述都可以包含空格,所以我不能在用逗号分隔之前删除空格以在每个描述周围添加单引号。我想删除单引号后的所有空格,因为没有描述会以空格开头。在 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 过程的 For Each 循环内。
【问题讨论】:
-
在循环中使用 str = str & item 的扩展性非常差,因为每个添加的项目都会使内存使用量翻倍。每增加 10 个项目,内存使用量就会增加大约 1000 倍。 StringBuilder 是在循环中构建字符串的首选,但根据我的建议,您根本不需要循环。