4

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

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

Comments

8

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)

Comments

4

Try this

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

1 Comment

Thanks, I did not know it infered the type even if it is a field of the class.great!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.