Reputation: 5047
I know I can use an anonymous method or a lambda expression, e.g:
myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10); });
myObjects.RemoveAll(m => m.X >= 10));
But I cannot figure out whether a regular delegate (delegate bool X (MyObject o) ) could be used, my attempts fail.
I.e. creating a delegate, set it to a method a then pass the delegate instance as the predicate.
Upvotes: 3
Views: 61
Reputation: 3853
For compatibility reasons, you must instantiate the delegate explicitly, even if the signature of a different delegate is compatible. This is not very well documented, see discussion in this question.
Example for the (very verbose) syntax do do this:
public void Test()
{
var l = new List<MyObject>();
// The following three lines
var x = new X(my => string.IsNullOrEmpty(my.Name));
var p = new Predicate<MyObject>(x);
l.RemoveAll(p);
// ...will accomplish the same as:
l.RemoveAll(my => string.IsNullOrEmpty(my.Name));
}
private delegate bool X(MyObject m);
private class MyObject
{
public string Name { get; set; }
}
Upvotes: 2