3

I have the following method definition (EDITED to remove redundant generic):

public static T SearchAgaistValues<T>(Dictionary<string, string> input, 
string key, List<T> values, Predicate<T> match, out string[] cmdParams)

My simplified requirements are as follows. I need to search input for key, and if found, see if its value appears in values. However, values is generic (and will obviously contain a string that I need to match). Therefore, the way I see it, I have to pass a predicate method to perform the matching.

However, every example of Predicate<T> I have seen has a hard coded comparitor. I need to compare the found key's value to each item in values. I cannot pass these values, however.

I can't see how to do this outside of a foreach loop with a delegate based match method.

Am I missing something here?

IamIC
  • 17,747
  • 20
  • 91
  • 154
  • 2
    What's the point of the type parameter T here? – FishBasketGordo Jul 12 '11 at 00:59
  • 2
    Also, if `values` is a generic list, but will contain a string that you need to match, do you mean that you need to match a string property of the objects in `values`, or what? Please clarify. – FishBasketGordo Jul 12 '11 at 01:03
  • 1
    " However, values is generic (and will obviously contain a string that I need to match)." I need to match exactly what you said. – IamIC Jul 12 '11 at 01:08

1 Answers1

5

As I see it you have two options, without changing crazy requirements.

Option 1 is to use Func<string, T1, bool> instead of Predicate<T1>. This way the predicate can convert between string and T1 as needed and return the boolean matched result.

public static T1 SearchAgaistValues<T, T1>(
            Dictionary<string, string> input, 
            string key, 
            List<T1> values, 
            Func<string, T1, bool> match, 
            out string[] cmdParams)

Alternatively you can pass an additional Converter<T1, string> parameter to convert the looked-up string to a T1 and then compare using the predicate.

public static T1 SearchAgaistValues<T, T1>(
            Dictionary<string, string> input, 
            string key, 
            List<T1> values, 
            Converter<T1, string> converter,
            Predicate<T1> match, 
            out string[] cmdParams)

Both cases are less than ideal though. This function sounds a lot more like a problem looking for a solution than the other way around. The signature is a bit crazy and seems like it can be greatly simplified by restating the requirements or breaking it up into pieces.

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
  • It started off innocently, but got a bit complex, then grew into wanting to learn how to do it properly. Perhaps it would be better to be less generic in this case. – IamIC Jul 12 '11 at 01:05