December 1, 2017
lambda expression with parameters
If there is a single parameter for lambda expression, just name of the parameter is sufficient as shown in below example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Func<string, string> oneParam = s => String.Format("change uppercase {0}", s.ToUpper()); Console.WriteLine(oneParam("test")); } } }
However, if we need to use two parameters, we put parameter names inside brackets:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Func<double, double, double> twoParams = (x, y) => x * y; Console.WriteLine(twoParams(3, 2)); } } }
We can also write the data types with the parameter names. This helps compiler to match with the exact overloaded version:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Func<double, double, double> twoParamsWithTypes = (double x, double y) => x * y; Console.WriteLine(twoParamsWithTypes(4, 2)); } } }
If a lambda expression is of single line, we don’t need a code block with curly brackets. For example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Func<double, double> square = x => x * x; Console.WriteLine( square(10) ); } } }
The above code is alternate notation for the following code. However, the above code is more readable.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Func<double, double> square = x => { return x * x; } Console.WriteLine( square(10) ); } } }
If we have multiple statements in the implementation of a lambda expression, then we need a return statement as well as curly brackets:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Func<string, string> lambda = param => { param += " HELLO "; param += " and this was added to the string."; return param; }; Console.WriteLine(param(" PAKISTAN ") ); } } }