C# Lambda Expressions with programming Examples
Description:
C# Lambda Expressions with Programming Examples: In this article, I am going to show you how to use lambda expressions in C# with step by step explanations.
C# Lambda expressions
With the delegates from C# 1.0 and 1.1, the language was given a way to generate pointers to code to be able to. C# 2.0 introduced anonymous methods to passcode pointers as arguments to methods. With the introduction of C# 3.5 the Anonymous method syntax has a clearer and simpler syntax. Furthermore, the C# lambda expressions create more possibilities, which are explained in this Article.
Introduction to C# Lambda Expressions
With the introduction of C# lambda expressions in C# 3.5, the syntax became more pronounced and simple.
C# Lambda Expressions Syntax:
1 2 3 4 5 |
(parameter_Input) => Expressions; And in block body: (parameter_Input) => {<Expressions>;} |
Example1: how to use simple Lambda Expression in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaExpressionDemo {    delegate int myDelegate(int i, int j);    class Program    {        static void Main(string[] args)        {            myDelegate add = (int i, int j) => { return i + j; };            Console.WriteLine("{0}", add(10, 4).ToString());            Console.ReadKey();        }    } } |
Output:
The delegate definition myDelegate(int i, int j) makes it clear that the parameters to be transferred from Type are int. Consequently, it is possible to change the expression syntax by dispensing with the redundant type information to simplify.
myDelegate add = (i, j) => {return i + j; };
If, as in the above example1, there is only one return statement in the expression body, even the curly brackets and the keyword return in the expression are also omitted.
1 |
myDelegate add = (i, j) => i + j; |
Using Func Delegate Types
With the keyword delegate, you can define any number of your own delegates, which may also be generic, can be
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaExpressionDemo {    public delegate T myDelegate<T>(T i, T j);    class Program    {        static void Main(string[] args)        {            myDelegate<int> add = (i, j) => i + j;            Console.WriteLine("{0}", add(10, 4).ToString());            Console.ReadKey();        }    } } |
Since the introduction of LINQ, there have also been various predefined delegate types (namespace System.Linq). The delegate Func <> is four times overloaded and supports up to four parameters and one Return parameters.
1 2 3 4 5 6 7 8 9 |
public delegate TR Func <TR> () public delegate TR Func <T, TR> (T arg) public delegate TR Func <T1, T2, TR> (T1 arg1, T2 arg2) public delegate TR Func <T1, T2, T3, TR> (T1 arg1, T2 arg2, T3 arg3) public delegate TR Func <T1, T2, T3, T4, TR> (T1 arg1, T2 arg2, T3 arg3, T4 arg4) |
TR defines the return type and is always last in the generic type list. Set T1 to T4 represents the different types of parameters. With the overload for a parameter you can do the above Rewrite the code example as follows:
Example2: how to use delegate type Func <> in C# :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaExpressionDemo { public delegate T Func<T, TResult>(T i, T j); class Program { static void Main(string[] args) { Func<int, int> add = (i, j) => i + j; Console.WriteLine("{0}", add(20, 4).ToString()); Console.ReadKey(); } } } |
Output:
Predicates and projections Uses in C# Lambda Expressions:
There are basically two types of C# lambda expressions: predicates3 and projections. A predicate delivers always returns true or false and expresses that a Boolean expression meets a condition or Not. A projection is a type of expression that differs from the parameter types.
Example3: how to use predicates of a C# lambda expressions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaExpressionDemo {       class Program    {        static void Main(string[] args)        {            List<string> customers = new List<string>();            customers.Add("Fawad khan");            customers.Add("Shaista");            customers.Add("XYX");            customers.Add("ABC");            string result = customers.Find(customer => customer.Equals("Fawad khan"));            List<string> results = customers.FindAll(c => c.Length > 5);            Console.WriteLine("Result: {0}", result);            foreach (string item in results)            {                Console.WriteLine("Result: {0}", item);            }            Console.ReadKey();        }    } } |
Output:
Example4 shows both types of C# lambda expressions again, using the predicate as a filter while the projections, such as s.ToUpper(), additional expressions or operations To run.
Example4: Â how to use Projection of a C# lambda expressions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaExpressionDemo {       class Program    {        // Func delegate        static Func<string, bool> filter = s => s.Length == 5; //Predicate        static Func<string, string> extract = s => s; //Projection        static Func<string, string> project = s => s.ToUpper(); //Projection        static void Main(string[] args)        {            List<string> customers = new List<string>();            customers.Add("Fawad khan");            customers.Add("Shaista");            customers.Add("ABC");            customers.Add("AXY");            if (filter(customers[1]))                Console.WriteLine(customers[1].Length.ToString());            Console.WriteLine(extract(customers[0]));            Console.WriteLine(project(customers[2]));            Console.ReadKey();        }    } } |
Output:
To emphasize once again the connection to the anonymous methods: instead of the predefined Func delegates one could also use the following definitions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
static Func <string, bool> filter = delegate (string s) { return s.Length == 5; }; static Func <string, string> extract = delegate (string s) { return s; }; static Func <string, string> project = delegate (string s) { return s.ToUpper (); }; |
C# lambda expressions trees:
It is possible to represent a C# lambda expressions as an expressions tree and, if necessary, to manipulate it. An expression tree thus represents a representation of a C# lambda expressions. Around a lambda expression To be able to convert into an expression tree, you need the namespace System.Linq.Expressions with the generic type Expression <T>.
Example5: Reading out an expression tree:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace LambdaExpressionDemo {       class Program    {               static void Main(string[] args)        {            int val = 4;            Expression<Func<int, bool>> exp = p => p < 7;            if (exp.Compile()(val))                Console.WriteLine("smaller than 7");            else                Console.WriteLine("greater than 7");            BinaryExpression body = (BinaryExpression)exp.Body;            ParameterExpression left = (ParameterExpression)body.Left; // p            ConstantExpression right = (ConstantExpression)body.Right; // 7            Console.WriteLine("{0} {1} {2} ", left.Name, body.NodeType, right.Value);            Console.ReadKey();        }    } } |
Output:
Example5 defines an expression for: p less than 7. You can use such a C# lambda expressions as in the This example can be executed by calling the Compile method or decomposed into its expression tree.
Conversely, it is also possible to generate a C# lambda expressions at runtime from an expression tree:
Example6: Generate C# lambda expressions using expression tree:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace LambdaExpressionDemo {       class Program    {               static void Main(string[] args)        {            int val = 4;            ParameterExpression parameterExpression = Expression.Parameter(typeof(int), "n");            ConstantExpression constExpression = Expression.Constant(7, typeof(int));            BinaryExpression lessThan = Expression.LessThan(parameterExpression, constExpression);            Expression<Func<int, bool>> lambdaExpression = Expression.Lambda<Func<int, bool>>(            lessThan,            new ParameterExpression[] { parameterExpression });            if (lambdaExpression.Compile()(val))                Console.WriteLine("smaller than 7");            else                Console.WriteLine("greater than 7");            Console.ReadKey();        }    } } |
Output:
Here, the functionality of the code from Listing example5 is illustrated by different expression definitions (ParameterExpression, ConstantExpression and BinaryExpression) recreated at runtime. About the generic Type Expression<T> the C# lambda expressions is generated in lambdaExpression and via the method Compile() executed. Table1 lists the most important expression classes for generation of an expression tree.
Classes for creating and displaying expression trees:
Table 1:
Type | Description |
Expression
Expression <T> |
Abstract base class of all expression classes.
The generic class that manages an expression tree and the C# lambda expressions in binary represents. |
BinaryExpression | BinaryExpression is used for expressions with two operands that the property values Own Left and Right. |
ConditionalExpression | The ConditionalExpression class is used to create a condition in an expression tree Are defined. |
ConstantExpression | The ConstantExpression class allows you to set a constant value that is contained in an Expression is used. |
LambdaExpression | This class represents a C# lambda expression that can be executed. |
MethodCallExpression | MethodCallExpression is used for expressions that represent a method call. |
ParameterExpression | This class defines the parameters that are used in an expression. |
UnaryExpression | UnaryExpression defines a unary expression that is contained in a C# lambda expressions is used. |
TypeBinaryExpression | This class defines an operation between an expression and a type. |