Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 632
John V Avatar asked Nov 29 '22 17:11

John V


2 Answers

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.)

like image 134
Jon Skeet Avatar answered Dec 05 '22 16:12

Jon Skeet


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)

like image 33
Marc Gravell Avatar answered Dec 05 '22 16:12

Marc Gravell