Robert Achmann Robert Achmann - 1 year ago 67
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:


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download