[英]Testing string for specific characters VB.NET
I have a string that has FTP permissions - "LRSDCWAN" Is there a more efficiant way of checking the relevent CheckBox if the string contains the relevant character? 我有一个具有FTP权限的字符串-“ LRSDCWAN”如果该字符串包含相关字符,是否有更有效的方法来检查relevent CheckBox?
If reader.Item("home_perm").Contains("L") Then
CBoxList.Checked = True
End If
If reader.Item("home_perm").Contains("R") Then
CBoxRead.Checked = True
End If
If reader.Item("home_perm").Contains("S") Then
CBoxSubDir.Checked = True
End If
If reader.Item("home_perm").Contains("D") Then
CBoxDelete.Checked = True
End If
If reader.Item("home_perm").Contains("C") Then
CBoxCreate.Checked = True
End If
If reader.Item("home_perm").Contains("W") Then
CBoxWrite.Checked = True
End If
If reader.Item("home_perm").Contains("A") Then
CBoxAppend.Checked = True
End If
If reader.Item("home_perm").Contains("N") Then
CBoxRename.Checked = True
End If
Thanks. 谢谢。
While it doesn't get rid of your .Contains() problem, you can simplify the logic quite a bit. 虽然它不能解决您的.Contains()问题,但是您可以简化逻辑。
If you notice, you are using: 如果您注意到,则使用的是:
If reader.Item("home_perm").Contains("L") Then
CBoxList.Checked = True
End If
You can simplify this by just saying 您可以简单地说一下
CBoxList.Checked = reader.Item("home_perm").Contains("L")
You can do this for all of your checkboxes. 您可以对所有复选框执行此操作。 It doesn't solve the needing to call contains, but it eliminates 2/3 of your lines of code. 它并不能解决需要调用contains的问题,但是可以消除代码行的2/3。
EDIT.. Doh, I missed the fact that it's a different checkbox for each character. 编辑.. Doh,我错过了每个字符都有不同复选框的事实。
Okay, in that case I'd use a Dictionary(Of Char, CheckBox)
for each character. 好的,在这种情况下,我将为每个字符使用一个Dictionary(Of Char, CheckBox)
。 Something like this - but in less broken VB :) 这样的东西-但在破碎的VB :)
' Assumes VB10 collection initializers
Dim map As New Dictionary(Of Char, CheckBox) From {
{ "L", CBoxList },
{ "R", CBoxRead },
{ "S", CBoxSubDir },
{ "D", CBoxDelete },
{ "C", CBoxCreate }
}
For Each c As Char In reader.Item("home_perm")
Dim cb As CheckBox
If map.TryGetValue(c, cb) Then
cb.Checked = True
End If
Next
Regular Expressions. 常用表达。
http://msdn.microsoft.com/en-us/library/hs600312(VS.71).aspx http://msdn.microsoft.com/zh-CN/library/hs600312(VS.71).aspx
OR 要么
string.indexof method: string.indexof方法:
Dim myString As String = "LRSDCW"
Dim myInteger As Integer
myInteger = myString.IndexOf("D") // myInteger = 4
myInteger = myString.IndexOf("N") // myInteger = -1
Use an Array for myInteger and check each member of the array for a value other than -1, if it is -1, don't check the box. 对myInteger使用一个数组,并检查该数组的每个成员是否为-1以外的值,如果它为-1,则不要选中该框。
您能否将所有比较值放入通用列表中并遍历该列表?
CBoxRename.Checked = (New Regex("[LRSDCWAN]").Match(reader.Item("home_perm")).Count > 0) ?
这是非常低效的-每次都是相对密集类的全新实例,因此您可以缓存一个实例并在需要时重用它,但是这样可以使它整齐地适合一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.