Lambda Expressions in C# Programming


Lambda expressions in C# provide a concise way to represent anonymous methods using a special syntax. They are widely used in LINQ queries, event handling, and with delegates. Lambda expressions allow you to write functions in a compact format, making your code cleaner and more readable.

Step 1: Understanding the Syntax of Lambda Expressions

A lambda expression has the following syntax:


    (parameters) => expression
        

Where parameters is a list of input parameters (can be empty), and expression is the body of the lambda, which can either be a single statement or a block of code.

Step 2: Simple Lambda Expression Example

Let’s start by creating a basic lambda expression that adds two numbers:


    using System;
   namespace LambdaExpressionExample
    {
        class Program
        {
            // Declare a delegate
            delegate int AddNumbers(int num1, int num2);
           static void Main()
            {
                // Assign a lambda expression to the delegate
                AddNumbers add = (num1, num2) => num1 + num2;
               // Call the lambda expression
                int result = add(5, 3);
                Console.WriteLine("The result of adding is: " + result);
               Console.ReadLine();
            }
        }
    }
        

In this example, the lambda expression (num1, num2) => num1 + num2 is assigned to the delegate AddNumbers. This lambda takes two parameters num1 and num2, and returns their sum. When invoked, it outputs 8 in this case.

Step 3: Lambda Expressions in LINQ Queries

Lambda expressions are commonly used with LINQ (Language Integrated Query) to query collections. Below is an example of how lambda expressions work in a LINQ query to filter an array of numbers:


    using System;
    using System.Linq;
   namespace LambdaInLINQExample
    {
        class Program
        {
            static void Main()
            {
                int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
               // Use a lambda expression to filter even numbers using LINQ
                var evenNumbers = numbers.Where(num => num % 2 == 0);
               // Display the filtered results
                Console.WriteLine("Even numbers:");
                foreach (var num in evenNumbers)
                {
                    Console.WriteLine(num);
                }
               Console.ReadLine();
            }
        }
    }
        

In this example, the lambda expression num => num % 2 == 0 is used to filter out even numbers from an array. The Where method uses this lambda expression to return only those numbers that satisfy the condition of being even.

Step 4: Lambda Expressions with Single Statements and Code Blocks

A lambda expression can be written with a single statement or a block of code. Below is an example showing both forms:


    using System;
   namespace LambdaStatementAndBlockExample
    {
        class Program
        {
            static void Main()
            {
                // Lambda with a single statement
                Func multiply = (a, b) => a * b;
                Console.WriteLine("Multiplication result: " + multiply(4, 5));
               // Lambda with a block of code
                Func subtract = (a, b) =>
                {
                    int result = a - b;
                    return result;
                };
                Console.WriteLine("Subtraction result: " + subtract(10, 4));
               Console.ReadLine();
            }
        }
    }
        

In the first example, the lambda expression (a, b) => a * b returns the result of multiplying the two numbers. In the second example, the lambda expression (a, b) => { ... } contains a block of code that performs subtraction and returns the result.

Step 5: Benefits of Using Lambda Expressions

Here are some key benefits of using lambda expressions in C#:

  • They make your code more concise and readable, especially for simple functions.
  • They are commonly used with LINQ to express queries in a more declarative style.
  • They are useful for defining short-term functions that don’t need to be reused.
  • They can be passed as arguments to methods and delegates.

Conclusion

Lambda expressions are a powerful feature in C# that allow you to write inline methods in a clean and expressive way. They are most commonly used with LINQ queries, delegates, and event handling. Understanding how to use lambda expressions can greatly enhance your ability to write more readable and maintainable code.




Advertisement