I am writing a table driven method in C#. I have a dictionary of this signature:
Diction<Func<string, bool>, Func<string>>
So it will take a string as a parameter and let me execute a method which returns a bool on the string (eg string.Length > 5). The value corresponds to methods which return a string.
But the method which does this takes a func as a parameter. I want to change this so it takes a string but then it looks at the string’s length and gets the right value from the dictionary.
Something like this:
dict[s.Length]; Or dict[s]; // Where s is a string
If it is greater than 5, it gets the Func which runs the method for the length > 5, otherwise it gets another func. I want to avoid using if/else as this is an exercise in coming out of that habit.
I could use ?: but this is only for two conditions. The main thing is this is for an API and I want the user of the API to just pass in the string as a parameter, and then look at the length and get the right func from the dictionary.
How best should I go about this?
Thanks
So it looks like you’re really just using the dictionary as a set of key-value pairs and you want to evaluate the “value” function for the first “key” predicate that returns true. Rather than a Dictionary (since you’re not really doing a lookup), I would use an array (anonymous here for convenience):