Help with Predicate<T> delegate
I am trying to create an overloaded Add method as an extension to the OrderedDictionary class and would like to add the key/value based on some curried predicate.
The calling code would look like this:
OrderedDictionary dict = new OrderedDictionary();
Predicate<int> lessThan5 = i=>; i < 5;
Predicate<string> lenOf2 = s=> s.length == 2;
dict.Add("01","Name", lessThan5 );
dict.Add("02","place", lenOf2);
I have created an extension method like so:
public static class CollectionExtensions
{
public st开发者_运维知识库atic void Add(this OrderedDictionary s, string k, string v, Predicate p)
{
if (p)
{
d.Add(k, v);
}
}
}
But it doesn't work because I get a compiler error reading "cannot convert Predicate to bool".
Does anyone know what I am missing?
Thanks for any help. -Keith
The issue is that you are not evaluating your predicate to check and see whether or not the predicate is satisfied. Now, it's not clear from your question if you want the predicate to test the key or the value. The following checks the key. You should also consider having the method return bool
indicating success or failure as I've done here.
static class OrderedDictionaryExtensions {
public static bool Add(
this OrderedDictionary dictionary,
string key,
string value,
Predicate<string> predicate
) {
if (dictionary == null) {
throw new ArgumentNullException("dictionary");
}
if (predicate == null) {
throw new ArgumentNullException("predicate");
}
if (predicate(key)) {
dictionary.Add(key, value);
return true;
}
return false;
}
}
Usage;
// dictionary is OrderedDictionary
dictionary.Add("key", "value", s => s.Length < 5);
You can actually generalize this a bit since OrderedDictionary
is not strongly-typed.
static class OrderedDictionaryExtensions {
public static bool Add<TKey, TValue>(
this OrderedDictionary dictionary,
TKey key,
TValue value,
Predicate<TKey> predicate
) {
if (dictionary == null) {
throw new ArgumentNullException("dictionary");
}
if (predicate == null) {
throw new ArgumentNullException("predicate");
}
if (predicate(key)) {
dictionary.Add(key, value);
return true;
}
return false;
}
}
Usage:
// dictionary is OrderedDictionary
dictionary.Add(17, "Hello, world!", i => i % 2 != 0);
精彩评论