Lambda Expressions in C#

Lambda expressions in C# are used like anonymous functions, with the difference that in Lambda expressions you don’t need to specify the type of the value that you input thus making it more flexible to use.
The ‘=>’ is the lambda operator which is used in all lambda expressions. The Lambda expression is divided into two parts, the left side is the input and the right is the expression.

The Lambda Expressions can be of two types:

  1. Expression Lambda: Consists of the input and the expression.

    Syntax:



    input => expression;
    
  2. Statement Lambda: Consists of the input and a set of statements to be executed.

    Syntax:

    input => { statements };
    

Let us take some examples to understand the above concept better.

Example 1: In the code given below, we have a list of integer numbers. The first lambda expression evaluates every element’s square { x => x*x } and the second is used to find which values are divisible by 3 { x => (x % 3) == 0 }. And the foreach loops are used for displaying.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the
// Lambda Expression
using System;
using System.Collections.Generic;
using System.Linq;
  
namespace Lambda_Exressions {
class Program {
    static void Main(string[] args)
    {
        // List to store numbers
        List<int> numbers = new List<int>() {36, 71, 12, 
                             15, 29, 18, 27, 17, 9, 34};
  
        // foreach loop to dislay the list
        Console.Write("The list : ");
        foreach(var value in numbers)
        {
            Console.Write("{0} ", value);
        }
        Console.WriteLine();
  
        // Using lambda expression
        // to calculate square of
        // each value in the list
        var square = numbers.Select(x => x * x);
  
        // foreach loop to display squares
        Console.Write("Squares : ");
        foreach(var value in square)
        {
            Console.Write("{0} ", value);
        }
        Console.WriteLine();
  
        // Using Lambda exression to
        // find all numbers in the list
        // divisible by 3
        List<int> divBy3 = numbers.FindAll(x => (x % 3) == 0);
  
        // foreach loop to display divBy3
        Console.Write("Numbers Divisible by 3 : ");
        foreach(var value in divBy3)
        {
            Console.Write("{0} ", value);
        }
        Console.WriteLine();
    }
}
}

chevron_right


Output:

The list : 36 71 12 15 29 18 27 17 9 34 
Squares : 1296 5041 144 225 841 324 729 289 81 1156 
Numbers Divisible by 3 : 36 12 15 18 27 9 

Example 2: Lambda expressions can also be used with user-defined classes. The code given below shows how to sort through a list based on an attribute of the class that the list is defined upon.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the
// Lambda Expression
using System;
using System.Collections.Generic;
using System.Linq;
  
// User defined class Student
class Student {
      
    // properties rollNo and name
    public int rollNo
    {
        get;
        set;
    }
      
    public string name
    {
        get;
        set;
    }
}
  
class GFG {
      
    // Main Method
    static void Main(string[] args)
    {
        // List with eah element of type Student
        List<Student> details = new List<Student>() {
            new Student{ rollNo = 1, name = "Liza" },
                new Student{ rollNo = 2, name = "Stewart" },
                new Student{ rollNo = 3, name = "Tina" },
                new Student{ rollNo = 4, name = "Stefani" },
                new Student { rollNo = 5, name = "Trish" }
        };
  
        // To sort the details list 
        // based on name of student
        // in acsending order
        var newDetails = details.OrderBy(x => x.name);
  
        foreach(var value in newDetails)
        {
            Console.WriteLine(value.rollNo + " " + value.name);
        }
    }
}

chevron_right


Output:

1 Liza
4 Stefani
2 Stewart
3 Tina
5 Trish


My Personal Notes arrow_drop_up

Student at Padre Conceicao College of Engineering, Goa Computer Engineering

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.