John V
John V

Reputation: 5047

Replacing delegate with lambda expression

I am trying to replace following statement with the lambda expression:

 List<ABC> l = new List<ABC>();
  l.Find(delegate(ABC a) { return a.A == 4; });

I tried

 l.Find((ABC a)=>a.A==4;);

but that is obviously incorrect. Thanks

Upvotes: 4

Views: 3060

Answers (4)

Niranjan Singh
Niranjan Singh

Reputation: 18290

Why do you not use it in simple way, I think there is no need to write (ABC a):

l.Find(a => a.A == 4);

This statement l.Find((a) => a.A == 4); can be written as your statement l.Find(delegate(ABC a) { return a.A == 4; });. As you seen predicate can be replaced with the anonymous method( delegate ).

(.NET 2.0)

 fooList.Find(delegate (Foo f) { return f.Equals(fooTarget); });

or (later version)

 fooList.Find(f => f.Equals(fooTarget));

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

Just to be complete, any of these would be valid:

// Fullest version
l.Find((ABC a) => { return a.A==4; });

// Infer the type of the parameter
l.Find((a) => { return a.A==4; });

// Single parameter - can remove the ()
l.Find(a => { return a.A==4; });

// Single expression - can remove braces and semi-colon
l.Find(a => a.A == 4);

(You can use the "single expression" part independently of the other shortcuts.)

Upvotes: 10

Marc Gravell
Marc Gravell

Reputation: 1062502

Firstly, note that it is still a delegate - simply: rather, it uses the lambda syntax rather than the anonymous method syntax (it essentially means exactly the same thing, though).

As for how to fix it: just take away the ;:

l.Find((ABC a) => a.A == 4);

or more simply:

l.Find(a => a.A == 4);

(brackets are only necessary if you have multiple parameters; explicit types are useful for disambiguation)

Upvotes: 8

Julien
Julien

Reputation: 1192

Try this

l.Find( (a) => a.A == 4);

Upvotes: 4

Related Questions