LINQ Lambda Expressions

In LINQ, Lambda expression is a function without a name. It makes the syntax short and precise. Though it is not as readable as a LINQ query, it is equally essential as the LINQ query and gets converted to lambda internally. Its scope is limited to where it is used as an expression. We cannot reuse it afterward.

LINQ Lambda Expressions Syntax

Following is the syntax of defining lambda expressions in LINQ.

 

(Input Parameter) => Method Expression

Lambda Expression is dynamic and decides the type in compile time. In the above lambda expression on the left-hand side, we have a bracket () containing the Input parameter.

 

The name of the parameter can be anything and ahead of this parameter (=>) is an Equal to (=) followed by a greater than (>) symbol is used to send or pass the input parameter from left to right side, and on the right-hand side, the operation is performed using the input parameter passed from the left-hand side parameters. This whole syntax forms a Lambda Expression.

 

Here we have an example to demonstrate what we have read so far. Let’s say we have an expression like as shown below.

 

X => X + 10

Here X is an input parameter followed by => operator, and next to the operator, there is an expression that adds numeric 10 to the input variable (X). So the output would increment the numeric 10 to the X variable, which was the input parameter on the left-hand side of the expression.

 

The following are examples of using LINQ lambda expressions in c# and vb.net.

LINQ Lambda Expressions Example in C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQExamples
{
   class Program
   {
     static void Main(string[] args)
     {
        List<string> countries = new List<string>();
        countries.Add("India");
        countries.Add("US");
        countries.Add("Australia");
        countries.Add("Russia");
        IEnumerable<string> result = countries.Select(x => x);
        foreach (var item in result)
        {
           Console.WriteLine(item);
        }
        Console.ReadLine();
     }
   }
}

LINQ Lambda Expressions Example in VB.NET

Module Module1
Sub Main()
Dim countries As New List(Of String)()
countries.Add("India")
countries.Add("US")
countries.Add("Australia")
countries.Add("Russia")
Dim result As IEnumerable(Of String) = countries.[Select](Function(x) x)
For Each item In result
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub
End Module

If you observe the above examples, we created a list object (countries) with country names, and we are using a lambda expression to select the countries from the list object (countries).

 

Here Select is the property that we use to select from a list. And x is the input parameter that is on the left-hand side of the expression followed by => operator. On the right-hand side of the expression is the same input parameter which denotes that we want to display the parameter without performing any operation. So we are not specifying any condition on it.

 

We will get the following result when we run the above LINQ lambda expressions example.

 

India
US
Australia
Russia

We will create one more example to dig further into the LINQ Lambda Expressions. In the following example, we have an integer array having elements from 1 to 10, and we will display only even elements from the array.

LINQ Lambda Expressions Example2 in C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQExamples
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      Console.WriteLine("Below are the even numbers");
      Console.WriteLine("");
      IEnumerable<int> evennumber = numbers.Where(x => x % 2 == 0);
      foreach (var item in evennumber)
      {
         Console.WriteLine(item + " is an even number");
      }
      Console.WriteLine("--------------------------------------------------");
      Console.WriteLine("Below are the Odd numbers");
      Console.WriteLine("");
      IEnumerable<int> oddnumber = numbers.Where(x => x % 2 != 0);
      foreach (var item in oddnumber)
      {
         Console.WriteLine(item + " is an odd number");
      }
      Console.ReadLine();
    }
  }
}

LINQ Lambda Expressions Example2 in VB.NET

Module Module1
Sub Main()
Dim numbers As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Console.WriteLine("Below are the even numbers")
Console.WriteLine("")
Dim evennumber As IEnumerable(Of Integer) = numbers.Where(Function(x) x Mod 2 = 0)
For Each item In evennumber
Console.WriteLine("{0} is an even number", item)
Next
Console.WriteLine("--------------------------------------------------")
Console.WriteLine("Below are the Odd numbers")
Console.WriteLine("")
Dim oddnumber As IEnumerable(Of Integer) = numbers.Where(Function(x) x Mod 2 <> 0)
For Each item In oddnumber
Console.WriteLine("{0} is an odd number", item)
Next
Console.ReadLine()
End Sub
End Module

In the above examples, we are trying to display the Even and Odd numbers separately from the array list (numbers). Here, the “Where” clause is used as a method in the list to specify the desired condition, and it is supplied by using the Lambda expression. We name an input parameter on the left-hand side, follow the => operator, and specify the condition to select only even numbers. Once the numbers are added into the variable named “evennumber” of type IEnumerable<int>, we loop through the collection using a foreach loop to get the result.

 

Similarly, we are finding the Odd numbers by modifying the condition in our Lambda Expression and storing the result in the variable named oddnumber of type IEnumerable<int> and looping further to get the desired result.

 

When we execute the above examples, we will get the following result.

 

Below are the even numbers

2 is an even number
4 is an even number
6 is an even number
8 is an even number
10 is an even number
--------------------------------------------------
Below are the Odd numbers

1 is an odd number
3 is an odd number
5 is an odd number
7 is an odd number
9 is an odd number

This is how we can use the Lambda Expressions in our applications to store the result in a variable of type IEnumerable<int>, and we can loop through it to display the values based on our requirements.