LAMBDA EXPRESSION

C sharpA lambda expression in c sharp is an anonymous method having parameters, a return type if we use the default delegate Func, but it has no name. The compiler in the presence of a lambda expression is able to automatically convert it to an instance of a delegate. There are two types of lambda expressions:

  • Expression lambda: (parameters) => expression is an anonymous method whose body consists of a single instruction. It is defined with a list of one or more arguments, the lambda symbol =>, and a valid C# expression.
  • Statement lambda: (parameters) => {} the body is not formed by a single instruction but by two or more that are enclosed in a block of code.

USE OF LAMBDA EXPRESSION

using System;
namespace LambdaExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string> hello = () => "Hello World!";
            Console.WriteLine(hello());
            Func<string,string> hello2 = (string nome) => $"Hello {nome}";
            Console.WriteLine(hello2("Mario"));
            Action hello3 = () => Console.WriteLine("Hello!");
            hello3();
            /*SUPPONIAMO DI CALCOLARE IL MASSIMO TRA DUE NUMERI INTERI
            IL TIPO DEI PARAMETRI SI PUO' OMETTERE IN QUANTO IL COMPILATORE
            E' IN GARDO DI INFERIRE IL GIUSTO TIPO*/
            Func<int,int,int> maxint = (num1,num2)=> Math.Max(num1,num2);
            Console.WriteLine(maxint(12,68));
             /*SUPPONIAMO DI CALCOLARE IL MASSIMO TRA TRE DOUBLE
            IL TIPO DEI PARAMETRI SI PUO' OMETTERE IN QUANTO IL COMPILATORE
            E' IN GARDO DI INFERIRE IL GIUSTO TIPO*/
            Func<double,double,double,double> maxdouble = (arg1,arg2,arg3) => Math.Max(Math.Max(arg1,arg2),arg3);
            Console.WriteLine(maxdouble(12.987,68.789,98.876));
            /*--DATA UNA CERTA DATA DI NASCITA LA PERSONA
            PUO' GUIDARE O MENO NELLO STATO ITALIANO.*/
            Func<DateTime,bool> canDrive = (data) => data.AddYears(18) <= DateTime.Today;
            Console.WriteLine(canDrive(new DateTime(2003,02,01)));
            /*--DATE IN INPUT DUE DATE VOGLIAMO SAPERE LA MAGGIORE*/
            Func<DateTime,DateTime,DateTime> maxData = (data1,data2)=> data1 > data2 ? data1 : data2;
            Console.WriteLine(maxData(new DateTime(2020,12,31),DateTime.Today));   
            /*--ESEMPIO DI STATEMENT LAMBDA*/
            Func<int,int,int> somma = (numero1,numero2) =>{
                return numero1+numero2;
            };
            Console.WriteLine(somma(10,5));   
            Console.WriteLine(HelloWorld("Mario"));
            MyClass mc = new MyClass("Mario");
            Console.WriteLine(mc.Nome);
        
        }
        static string Hello(string nome)
        {
            return $"Ciao {nome}";
        }
        /*EXPRESSION-BODYED MEMBERS*/
        static string HelloWorld(string nome) => $"Hello World {nome}";
    }
    /*EXPRESSION-BODYED MEMBERS*/
    public class MyClass
    {
        private string nome;
        public string Nome
        {
            get => nome.ToUpper();
            set => nome=value;
        }
        /*EXPRESSION-BODYED MEMBERS*/
        public MyClass(string nome) => Nome = $"Ciao {nome}";
    }
}

LAMBDA EXPRESSION IN C SHARP THE EXPRESSION-BODYED MEMBERS

The lambda operator is also used in different circumstances than the one we have dealt with so far, that is, for members that have a body with a single expression, methods, constructors, properties.

using System;
namespace LambdaExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string> hello = () => "Hello World!";
            Console.WriteLine(hello());
            Func<string,string> hello2 = (string nome) => $"Hello {nome}";
            Console.WriteLine(hello2("Mario"));
            Action hello3 = () => Console.WriteLine("Hello!");
            hello3();
            /*SUPPONIAMO DI CALCOLARE IL MASSIMO TRA DUE NUMERI INTERI
            IL TIPO DEI PARAMETRI SI PUO' OMETTERE IN QUANTO IL COMPILATORE
            E' IN GARDO DI INFERIRE IL GIUSTO TIPO*/
            Func<int,int,int> maxint = (num1,num2)=> Math.Max(num1,num2);
            Console.WriteLine(maxint(12,68));
             /*SUPPONIAMO DI CALCOLARE IL MASSIMO TRA TRE DOUBLE
            IL TIPO DEI PARAMETRI SI PUO' OMETTERE IN QUANTO IL COMPILATORE
            E' IN GARDO DI INFERIRE IL GIUSTO TIPO*/
            Func<double,double,double,double> maxdouble = (arg1,arg2,arg3) => Math.Max(Math.Max(arg1,arg2),arg3);
            Console.WriteLine(maxdouble(12.987,68.789,98.876));
            /*--DATA UNA CERTA DATA DI NASCITA LA PERSONA
            PUO' GUIDARE O MENO NELLO STATO ITALIANO.*/
            Func<DateTime,bool> canDrive = (data) => data.AddYears(18) <= DateTime.Today;
            Console.WriteLine(canDrive(new DateTime(2003,02,01)));
            /*--DATE IN INPUT DUE DATE VOGLIAMO SAPERE LA MAGGIORE*/
            Func<DateTime,DateTime,DateTime> maxData = (data1,data2)=> data1 > data2 ? data1 : data2;
            Console.WriteLine(maxData(new DateTime(2020,12,31),DateTime.Today));   
            /*--ESEMPIO DI STATEMENT LAMBDA*/
            Func<int,int,int> somma = (numero1,numero2) =>{
                return numero1+numero2;
            };
            Console.WriteLine(somma(10,5));   
            Console.WriteLine(HelloWorld("Mario"));
            MyClass mc = new MyClass("Mario");
            Console.WriteLine(mc.Nome);
        
        }
        static string Hello(string nome)
        {
            return $"Ciao {nome}";
        }
        /*EXPRESSION-BODYED MEMBERS*/
        static string HelloWorld(string nome) => $"Hello World {nome}";
    }
    /*EXPRESSION-BODYED MEMBERS*/
    public class MyClass
    {
        private string nome;
        public string Nome
        {
            get => nome.ToUpper();
            set => nome=value;
        }
        /*EXPRESSION-BODYED MEMBERS*/
        public MyClass(string nome) => Nome = $"Ciao {nome}";
    }
}

DEEPENING

A lambda expression in C# is an anonymous function that can contain expressions or blocks of instructions and can be used to create delegates or expression tree expressions. Lambda expressions are particularly useful in LINQ (Language Integrated Query) operations to perform operations such as filtering, sorting, and transforming data.

Syntax of Lambda Expressions

The basic syntax of a lambda expression is as follows:

(parameters) => expression

Or, if the lambda expression contains an instruction block:

(parameters) => {
    // statements
}

Example of Lambda Expression

Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25

Parts of a Lambda Expression

1. Parameters: The parameters of the lambda expression are enclosed in parentheses. If the lambda accepts no parameters, the parentheses are empty. If it has multiple parameters, they are separated by commas. If it has only one parameter, the parentheses can be omitted.

(x, y) => x + y

2. Lambda operator (=>): The lambda operator “=>,” also called the arrow operator, separates the parameters from the body part of the lambda expression.

3. Expression or Statements: The part following the arrow can be a single expression or a block of instructions. If it is a single expression, the result of that expression is returned automatically. If it is a block of instructions, the return statement must be used to return a value.

Types of Lambda Expressions

1. Lambda expression (Expression Lambdas): These consist of a single expression.

Func<int, bool> isEven = x => x % 2 == 0;

2. Instruction Lambda Expressions (Statement Lambdas): They contain a block of instructions.

Action<string> greet = name =>
{
   string greeting = $”Hello, {name}!”;
Console.WriteLine(greeting);
};

Using Lambda Expressions

Lambda expressions are often used with delegates and generic types such as Func, Action, and Predicate.

  • Func<T, TResult>: Represents a delegate that accepts one or more parameters and returns a value.

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(3, 4)); // Output: 7

  • Action: Represents a delegate that accepts one or more parameters and does not return a value.

Action<string> print = message => Console.WriteLine(message);
print(“Hello, World!“); // Output: Hello, World!

  • Predicate: Represents a delegate that accepts a parameter and returns a boolean value.

Predicate<int> isPositive = number => number > 0;

Console.WriteLine(isPositive(5)); // Output: True

Lambda Expressions and LINQ.

Lambda expressions are widely used in LINQ queries to manipulate collections of data declaratively.

Example of LINQ with Lambda Expressions

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

foreach (var num in evenNumbers)
{
     Console.WriteLine(num); // Output: 2 4 6
}

In this example, n => n % 2 == 0 is a lambda expression that is passed to the Where method to filter out even numbers.

Conclusion

Lambda expressions in C# are powerful tools for writing concise and readable code, especially when working with delegates and LINQ. They allow inline functions to be defined without having to explicitly declare a method, improving maintainability and code clarity.

LINK TO PREVIOUS POST

LINK TO THE CODE ON GITHUB