Dec 8, 2014

Lambda Expressions

A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name. 

lambda expressions for Convenience. It's a shorthand that allows you to write a method in the same place you are going to use it. Especially useful in places where a method is being used only once, and the method definition is short. It saves you the effort of declaring and writing a separate method to the containing class. 


 Simple example

 

  • n is the input parameter
  • n % 2 == 1 is the expression
You can read n => n % 2 == 1 like: "input parameter named n goes to anonymous function which returns true if the input is odd".

Same example (now execute the lambda):

List<int> numbers = new List<int>{11,37,52};
List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();
 //Now oddNumbers is equal to 11 and 37





 

No comments:

Post a Comment