Lambda expressions
suggest changeLambda expressions 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<int> {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, parentheses may be omitted. You can include parentheses if you wish:
.Select( (number) => number * number);
or explicitly type the parameter, but then parentheses 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; } );
Select returns a new IEnumerable<int> with the computed values.
The second lambda expression sums the numbers in the list returned from Select. 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 );