Reputation: 85116
Not sure if I have the title right on this one, feel free to correct me.
I have code similar to the following:
string myValue = "aaa";
List<ListItem> myList = CreateMyList();
myList.Find(t=>t.Value == myValue );
I would like to create a Predicate function that does the same thing. I am able to implement it if I do not need to pass in myValue
:
...
List<ListItem> myList = CreateMyList();
myList.Find(SelectByValue);
...
}
static bool SelectByValue(ListItem li)
{ //***myValue is now hardcoded***
return li.Value == "aaa";
}
But I would like to be able to specify what "aaa" should be when I make the call to the predicate function. How can this be done?
Upvotes: 1
Views: 191
Reputation: 1502816
Rather than returning a bool, make it return a Predicate<ListItem>
:
static Predicate<ListItem> SelectByValue(String target)
{
return delegate(ListItem li) { return li.Value == target; };
}
Then call the method:
myList.Find(SelectByValue("foo"));
Note that C# 3 introduces lambda expressions making this slightly simpler:
static Predicate<ListItem> SelectByValue(String target)
{
return li => li.Value == target;
}
... and in .NET 3.5 and higher, it's generally more idiomatic to use LINQ than the List<T>
-specific methods.
Upvotes: 5
Reputation: 35146
static Predicate<ListItem> SelectByValue(string value)
{
return item=>li.Value == value;
}
Upvotes: 3