user2609980
user2609980

Reputation: 10484

How to change delegate expression to lambda?

I was reading some code and saw the following:

Method.Find(delegate(Department depts) { 
     return depts.Id == _departmentId; });

The T Find method has the following description:

public T Find(Predicate<T> match);
// Summary:
//     Searches for an element that matches the conditions defined by the specified
//     predicate, and returns the first occurrence within the entire 
//     System.Collections.Generic.List<T>.
//
// Parameters:
//   match:
//     The System.Predicate<T> delegate that defines the conditions of the element
//     to search for.
// (...)

Is it possible to rewrite this method to take a lambda expression as a parameter, and if so, how?

Upvotes: 0

Views: 81

Answers (2)

Sam Leach
Sam Leach

Reputation: 12956

No need to re-write the method, you can use a lambda already, as below:

Method.Find(x => x.Id == _departmentId );

The code you provide is an anonymous delegate

Method.Find(delegate(Department depts) { 
 return depts.Id == _departmentId; });

a lambda is an anonymous function.

Upvotes: 1

Servy
Servy

Reputation: 203819

The method can already accept a lambda expression as a parameter, if you want to pass one to it.

The method simply indicates that it accepts a delegate. There are several ways of defining a delegate:

  1. A lambda (Find(a => true))
  2. An anonymous delegate (what you used in your example)
  3. A method group Find(someNamedMethod)
  4. Reflection (Find((Predicate<Whatever>)Delegate.CreateDelegate(typeof(SomeClass), someMethodInfo)))

Upvotes: 5

Related Questions