Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Predicates in C#

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?

like image 313
IamIC Avatar asked Jun 29 '26 12:06

IamIC


1 Answers

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.

like image 170
Samuel Neff Avatar answered Jul 01 '26 01:07

Samuel Neff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!