Lambda Expressions in C#

Introduction

Lambda expressions are how anonymous functions are created.

Lambda expressions are anonymous functions that contain expressions or sequence of operators. All lambda expressions use the lambda operator =>, that can be read as “goes to” or “becomes”.

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. Usually lambda expressions are used as predicates or instead of delegates (a type that references a method).

Expression Lambdas

    Parameter => expression
    Parameter-list => expression
    Count => count + 2;
    Sum => sum + 2;
    n => n % 2 == 0

The lambda operator => divides a lambda expression into two parts. The left side is the input parameter and the right side is the lambda body.

Simple Lambda Expression Example 1

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. public static class demo  
  5. {  
  6.     public static void Main()  
  7.     {  
  8.         List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };  
  9.         List<int> evenNumbers = list.FindAll(x => (x % 2) == 0);  
  10.   
  11.         foreach (var num in evenNumbers)  
  12.         {  
  13.             Console.Write("{0} ", num);  
  14.         }  
  15.         Console.WriteLine();  
  16.         Console.Read();  
  17.   
  18.     }  
  19. }  
Output

    2 4 6

Simple Lambda expression

The preceding example loops through the entire collection of numbers and each element (named x) is checked to determine if the number is a multiple of 2 (using the Boolean expression (x % 2) == 0).

Example 2

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. class Dog  
  5. {  
  6.     public string Name { getset; }  
  7.     public int Age { getset; }   
  8. }    
  9. class demo{  
  10.     static void Main()  
  11.     {  
  12.         List<Dog> dogs = new List<Dog>() {   
  13.             new Dog { Name = "Rex", Age = 4 },  
  14.             new Dog { Name = "Sean", Age = 0 },  
  15.             new Dog { Name = "Stacy", Age = 3 }  
  16.          };  
  17.          var names = dogs.Select(x => x.Name);  
  18.          foreach (var name in names)  
  19.          {  
  20.              Console.WriteLine(name);  
  21.               
  22.          }  
  23.          Console.Read();  
  24.     }  
  25. }  
Output

    Rex
    Sean
    Stacy

Output

We 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 the dog's names. With the keyword var, we tell the compiler to define the type of the variable depending on the result that we assigned on the right side of the equals sign.

Using Lambda Expressions with Anonymous Types

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. class Dog  
  5. {  
  6.    public string Name { getset; }  
  7.    public int Age { getset; }   
  8. }    
  9. class demo{  
  10.    static void Main()  
  11.    {  
  12.       List<Dog> dogs = new List<Dog>() {   
  13.          new Dog { Name = "Rex", Age = 4 },  
  14.          new Dog { Name = "Sean", Age = 0 },  
  15.          new Dog { Name = "Stacy", Age = 3 }  
  16.       };  
  17.       var newDogsList = dogs.Select(x => new { Age = x.Age, FirstLetter = x.Name[0] });  
  18.       foreach (var item in newDogsList)  
  19.       {   
  20.          Console.WriteLine(item);  
  21.       }   
  22.       Console.Read();  
  23.    }  
  24. }  
Output

    { Age = 4, FirstLetter = R }
    { Age = 0, FirstLetter = S }
    { Age = 3, FirstLetter = S }

Using Lambda Expressions with Anonymous Types

The newly created collection newDogsList has elements of an anonymous type taking the properties Age and FirstLetter as parameters.

Sorting

The following is an examle of sorting with a lambda expression:

  1. var sortedDogs = dogs.OrderByDescending(x => x.Age);  
  2. foreach (var dog in sortedDogs)   
  3. {  
  4.    Console.WriteLine(string.Format("Dog {0} is {1} years old.", dog.Name, dog.Age));  
  5. }  
Output

    Dog Rex is 4 years old.
    Dog Stacy is 3 years old.
    Dog Sean is 0 years old.

Sorting with lambda expression

Thank you.

Up Next
    Ebook Download
    View all
    Learn
    View all