Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare a Predicate Delegate inline?

Tags:

c#

delegates

So I have an object which has some fields, doesn't really matter what. I have a generic list of these objects.

List<MyObject> myObjects = new List<MyObject>(); myObjects.Add(myObject1); myObjects.Add(myObject2); myObjects.Add(myObject3); 

So I want to remove objects from my list based on some criteria. For instance, myObject.X >= 10. I would like to use the RemoveAll(Predicate<T> match) method for to do this.

I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.

like image 945
Curtis Avatar asked Sep 12 '08 14:09

Curtis


People also ask

What is a predicate delegate in Linq?

A Predicate delegate is an in-built generic type delegate. This delegate is defined under System namespace. It works with those methods which contain some set of criteria and determine whether the passed parameter fulfill the given criteria or not.

Is predicate a delegate?

Predicate is the delegate like Func and Action delegates. It represents a method containing a set of criteria and checks whether the passed parameter meets those criteria. A predicate delegate methods must take one input parameter and return a boolean - true or false.

How do you call a predicate in C#?

C# Predicate with anonymous method var data = new List<int> { 1, -2, 3, 0, 2, -1 }; Predicate<int> isPositive = delegate(int val) { return val > 0; }; var filtered = data. FindAll(isPositive); Console. WriteLine(string. Join(",", filtered));

What are func and predicate delegates in C#?

The Func delegate takes zero, one or more input parameters, and returns a value (with its out parameter). Action takes zero, one or more input parameters, but does not return anything. Predicate is a special kind of Func.


2 Answers

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

like image 158
Erik van Brakel Avatar answered Sep 20 '22 19:09

Erik van Brakel


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.

like image 29
Mark Brackett Avatar answered Sep 20 '22 19:09

Mark Brackett