Tuesday, 19 April 2016

Lambda Expressions

Lambda expressions are anonymous functions that contain expressions or sequence of operators. All lambda expressions use the lambda operator =>, which can be read as “goes to”. The idea of the lambda expressions in C# is borrowed from the functional programming languages (e.g. Haskell, Lisp, Scheme, F# and others). The left side of the lambda operator specifies the input parameters and the right side holds an expression or a code block that works with the entry parameters and conceivably returns some result.
Usually lambda expressions are used as predicates or instead of delegates (a type that references a method instance), which can be applied on collections, processing their elements and/or returning a certain result.
 

Lambda Expressions – Examples
 

As an example, let’s take the extension method FindAll(…), which can be used to filter the necessary elements. It works on a certain collection by applying a given predicate on it that checks if an element matches a certain requirement. In order to use it we have to add a reference to the assembly System.Core.dll (if it is not already added) and include the namespace System.Linq, because the extension methods for the collections are there.
For example, if we want to take only the even numbers from a collection of integers, we can use the method FindAll(…) on that collection, passing a lambda method to it that checks if a certain number is even:

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };
List<int> evenNumbers = list.FindAll(x => (x % 2) == 0);
foreach (var num in evenNumbers)
{
Console.Write("{0} ", num);
}
Console.WriteLine();

The result is:
2 4 6


The example above loops through the whole collection of numbers and for each element (named x) a check, if the number is multiple of 2, is made (through the Boolean expression (x % 2) == 0).
Let’s now focus on an example in which trough an extension method and a lambda expression we will create a collection, containing data from a certain class. In the example, from the class Dog (with properties Name and Age), we want to get a list that contains all dogs’ names. We can do that with the extension method Select(…) (defined in the namespace System.Linq) by assigning to it to turn each dog (x) into dog’s name (x.Name) and writing that result in the variable names. With the keyword var, we tell the compiler to define the type of the variable according to the result that we assign on the right side of the equals sign.

No comments:

Post a Comment