Lambda expresions C# with Example



Lambda expresions C# with Example

Lambda Expresions are an extension of anonymous methods that allow for implicitly typed parameters and return 
values. Their syntax is less verbose than anonymous methods and follows a functional programming style. 
using System; 
using System.Collections.Generic; 
using System.Linq; 
public class Program 
{ 
public static void Main() 
{ 
var numberList = new List {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 
var sumOfSquares = numberList.Select( number => number * number ) 
.Aggregate( (int first, int second) => { return first + second; } ); 
Console.WriteLine( sumOfSquares ); 
} 
} 
The above code will output the sum of the squares of the numbers 1 through 10 to the console. 
The first lambda expression squares the numbers in the list. Since there is only 1 parameter parenthesis may be 
omitted. You can include parenthesis if you wish: 
.Select( (number) => number * number); 
or explicitly type the parameter but then parenthesis are required: 
.Select( (int number) => number * number); 
The lambda body is an expression and has an implicit return. You can use a statement body if you want as well. 
This is useful for more complex lambdas. 
.Select( number => { return number * number; } ); 
The select method returns a new IEnumerable with the computed values. 
The second lambda expression sums the numbers in list returned from the select method. Parentheses are 
required as there are multiple parameters. The types of the parameters are explicitly typed but this is not 
necessary. The below method is equivalent. 
.Aggregate( (first, second) => { return first + second; } ); 
As is this one: 
.Aggregate( (int first, int second) => first + second ); 

0 Comment's

Comment Form

Submit Comment