LINQ Lambda Expressions – Introduction

Lambda expression is actually a function without a defined name. Useful in places where a method is being used only once, and the method definition should be short and simple. It saves you the effort of declaring and writing a separate method.

Though it is not as readable as a LINQ query, internally the LINQ query also gets converted to lambda expression.

The best advantage is when reading the code, you don’t need to look elsewhere for the method’s definition.

Lambda basic syntax: Parameters => To be executed code

The left side of the code includes input parameters and the right side of it will contain the to be executed expression

Let’s have a simple example here:

N => N*2

Here at the left-hand side “N” is our input parameter and on the right-hand-side, there is an expression that actually multiplies the input variable “N”.


Let’s write a program to print the squares of the numbers

Our Data Source:
List<double> myNum_List = new List<double> { 1, 2, 3, 4 ,5 ,6 ,7 ,8 ,9 ,10 }

LINQ Lambda Expression Syntax Example using C#

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

namespace LinqExamplesCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<double> myNum_List = new List<double> { 1, 2, 3, 4 ,5 ,6 ,7 ,8 ,9 ,10 };
            //Using LINQ Lambda expression to print squares of numbers
            IEnumerable<double> myresults = myNum_List.Select(N => Math.Pow(N,2));

            foreach (var item in myresults)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
Output:
1
4
9
16
25
36
49
64
81
100

LINQ Lambda Expression Example using VB.Net

Module Module1
    Sub Main()

        Dim myNum_list As Double() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        'Using LINQ Lambda expression to print squares of numbers
        Dim myResults As IEnumerable(Of Double) = myNum_list.Select(Function(N) Math.Pow(N, 2))

        For Each item In myResults
            Console.WriteLine(item)
        Next
        Console.ReadLine()
    End Sub
End Module
Output:
1
4
9
16
25
36
49
64
81
100

Previous topic : LINQ Syntax – Quick Guide
Next Topic: LINQ Aggregate Functions

For more articles on LINQ, Click here

1 thought on “LINQ Lambda Expressions – Introduction

  1. […] topic: LINQ Lambda Expressions Next Topic: LINQ Filtering […]

Leave a Reply

%d bloggers like this: