Robert Achmann Robert Achmann - 3 months ago 8
C# Question

Validate string value against known list of values

I need to build a validation function, call it, say, 'isValid'

The known valid string values are like:

"01"
"06"
"15"
"22"
"40"
"DA"
"F2"


The input is a string of unknown content.

the function prototype, contained by a static class, which hold the valid known values, is:

public static bool isValid(string val);


What is the most efficient algorithm to do this?

I could use a

List<string> ValidKnownValues


and just see if ValidKnownValues.Contains(val)

I could use a switch statement on val, returning false on Default case

I could just compare string values

Is there a best practices approach to this simple small problem?

Answer

You could use use a HashSet<string> rather than a List<string> as this has a O(1) contains method so is very quick to look up valid known values.

http://msdn.microsoft.com/en-us/library/bb356440%28v=vs.110%29.aspx

Comments