Reputation: 1054
I have a total of 102 values associated with a fieldname called ArrivedFlag
.
Then I have a TextBox
control with an id of txtFlag
on the markup page.
In my codebehind, I have an if statement that says:
If txtFlag <> "value1" and txtFlag <> "another value" Then
lblMessage.Text ="You don't have the ability to view details"
end if
This works fine.
However, given that there are 102 values, I feel that doing an IF statement 102 times is a bit inefficient.
Does anyone know of a better way to handle this?
Dim allowedFlags = New List(Of String)()
With { _
"value1", _
"another value"
}
End With
If Not allowedFlags.Contains(txtFlag) Then
lblMessage.Text = "You don't have the ability to view details"
End If
Upvotes: 2
Views: 98
Reputation: 160912
Put your allowed values into an array and then just query whether the user's choice is in the array:
if(!allowedFlags.Contains(txtFlag))
lblMessage.Text ="You don't have the ability to view details";
Even better you can use a HashSet<string>
for the allowed values so you have O(1) lookup time.
Upvotes: 2
Reputation: 15931
add the values to a list,and then use .Contains
// hopefully you can get the 102 strings from an xml document or db
var listOfFlags = new List<string> { "value1", "another value", .... };
if (!listOfFlags.Contains(txtFlag))
{
lblMessage.Text = "you dont' have ..."
}
Upvotes: 2
Reputation: 901
A "switch" statement would be cleaner, though 102 "cases" would still be kind of messy. If you went with a strategy pattern, you would likely experience some measure "class explosion".
I'd probably start with a switch statement and then look at extracting some common behaviors and heading towards a strategy pattern.
Upvotes: 2