How do you declare a Predicate Delegate inline?
There's two options, an explicit delegate or a delegate disguised as a lamba construct:
explicit delegate
myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; });
lambda
myObjects.RemoveAll(m => m.X >= 10);
Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs
//C# 2.0
RemoveAll(delegate(Foo o){ return o.X >= 10; });
or
//C# 3.0
RemoveAll(o => o.X >= 10);
or
Predicate<Foo> matches = delegate(Foo o){ return o.X >= 10; });
//or Predicate<Foo> matches = o => o.X >= 10;
RemoveAll(matches);
The lambda C# 3.0 way:
myObjects.RemoveAll(m => m.x >= 10);
The anonymous delegate C# 2.0 way:
myObjects.RemoveAll(delegate (MyObject m) {
return m.x >= 10;
});
And, for the VB guys, the VB 9.0 lambda way:
myObjects.RemoveAll(Function(m) m.x >= 10)
Unfortunately, VB doesn't support an anonymous delegate.