Lambda Expression in LINQ Statements in C#

Naila Saad Siddiqui Feb 15, 2024
  1. LINQ in C#
  2. Syntax of LINQ in C#
  3. Lambda Expressions in C#
  4. Lambda Expression in LINQ
Lambda Expression in LINQ Statements in C#

This simple article is about Lambda expressions in LINQ Select queries. For that, we will first discuss a brief introduction to LINQ, its syntaxes, and Lambda expressions.

Furthermore, we will explain how we can use lambda expressions in LINQ Select queries.

LINQ in C#

LINQ is an acronym for Language Integrated Query. It is a uniform format to query the data from multiple data sources like objects, XML, SQL data servers, data sets, etc.

The only requirement for that data source is that it implements the IEnumerable<T> interface.

LINQ provides multiple advantages:

  1. LINQ offers object-based, language-integrated querying no matter where the data originated. Therefore, we can query databases, XML, and collections using LINQ.
  2. Checking the syntax at compile time.
  3. It enables you to query collections, such as arrays, enumerable classes, etc., in your application’s native language, such as VB or C#, much like you would query a database using SQL.

Consider a scenario where we have a list of numbers and must select numbers less than 10. Then, the LINQ query can help us choose the data.

Let’s look at the code segment below:

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp6 {
  class Program {
    static void Main(string[] args) {
      List<int> listOfNumbers = new List<int>() { 16, 11, 2, 5, 9, 8, 7, 6, 1, 12 };
      var result = from l in listOfNumbers
          where l<10 select l;
      foreach (int i in result) Console.WriteLine(i);
    }
  }
}

You can see from the LINQ query above that this is similar to the query syntax we use for querying data from SQL databases. Here, we are querying data from a local data member List.

The output of the code segment will be:

Output of LINQ

Syntax of LINQ in C#

There are two syntaxes of LINQ that are used while programming with LINQ:

  1. Query Syntax
  2. Method Syntax

Query Syntax in LINQ

The LINQ query syntax comprises a set of query keywords defined in the .NET Framework version 3.5 or higher. This enables programmers or developers to write SQL-style commands in code (C# or VB.NET) without using quotes.

It is also referred to as the Query Expression Syntax.

The from keyword starts the LINQ query syntax and ends with the Select or GroupBy keyword. Following the keyword, you can use various Standard Query Operations such as filtering, grouping, and so on to meet your needs.

The example below uses the query syntax to get the data from the list:

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

class LinqExample {
  static public void Main() {
    List<string> myList = new List<string>() { "Cat", "Dog", "Tiger", "Wolf" };

    // Create LINQ Query
    var result = from a in myList select a;

    // Executing the query
    foreach (var r in result) {
      Console.WriteLine(r);
    }
  }
}

This will generate the following output:

Output of Query Syntax

Method Syntax in LINQ

Method Syntax is used in LINQ to invoke the extension methods of the Enumerable or Queryable static classes. It’s also referred to as Method Extension Syntax.

The compiler, on the other hand, always converts query syntax to method syntax at compile time. It can use standard query operators like Select, Where, GroupBy, Join, Max, etc.

You may directly call them without using query syntax.

In the example below, we will use method syntax to get the name of an animal whose name length is greater than 3. The query will be formed like this:

var result = myList.Where(a => a.Length > 3);

The complete code for the method syntax will be like this:

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

class LinqExample {
  static public void Main() {
    List<string> myList = new List<string>() { "Cat", "Dog", "Tiger", "Wolf" };

    // Create LINQ Query
    var result = myList.Where(a => a.Length > 3);

    // Executing the query
    foreach (var r in result) {
      Console.WriteLine(r);
    }
  }
}

This will give the following output:

Output of Method Syntax

In the method syntax, you may notice an expression in the argument of the Where function consisting of a => sign. This unusual thing is known as the Lambda expression.

In the next section, we will discuss Lambda expression and its use with LINQ queries.

Lambda Expressions in C#

In C#, lambda expressions are used similarly to anonymous functions, with the exception that you don’t have to specify the type of the value you input when using a lambda expression, making it more flexible.

All lambda expressions use the lambda operator, represented by the symbol =>. The input is on the left side of the lambda expression, and the expression is on the right.

Lambda expressions are categorized into two forms:

  1. Expression Lambda
  2. Statement Lambda

Expression Lambda

This comprises an input statement and an expression to be evaluated on the right of the lambda symbol:

input statement => expression

Statement Lambda

This comprises an input statement and a set of statements on the right side of the lambda symbol:

input statements => { set of statements }

Suppose we have a List data structure that consists of some numbers, and we need to evaluate the cube of all the list numbers. This can be done very simply using the lambda expression.

This can be demonstrated in the code segment below:

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

namespace ConsoleApp6 {
  class Program {
    static void Main(string[] args) {
      List<int> listOfNumbers = new List<int>() { 16, 11, 2, 5, 9, 8, 7, 6, 1, 12 };
      var cubes = listOfNumbers.Select(a => a * a * a);

      // Display all the cubes
      Console.Write("Cubes of the List : ");
      foreach (var val in cubes) {
        Console.Write("{0} ", val);
      }
    }
  }
}

You can see in the code segment above that we have selected an element from the list using the Select function and then made its cube using the lambda expression.

The output of the segment will be as follows:

Output of Expression Lambda

Lambda Expression in LINQ

Lambda expression and LINQ provide a way to query the data from any data source. Here are a few examples in which we will query data using LINQ Lambda Syntax.

Suppose we have a user-defined class of Student with roll_num, name, and marks as their properties. We will initialize some data in the list of students and then query the data using LINQ queries and lambda expressions.

class Student {
  private int roll_num;
  private string name;
  private int marks;

  public int Roll_num {
    get => roll_num;
    set => roll_num = value;
  }
  public string Name {
    get => name;
    set => name = value;
  }
  public int Marks {
    get => marks;
    set => marks = value;
  }
}

In our Main function, we will create a list of Student classes and then query the data from it:

static void Main(string[] args) {
  List<Student> students =
      new List<Student>() { new Student { Roll_num = 1, Name = "David", Marks = 65 },
                            new Student { Roll_num = 2, Name = "John", Marks = 90 },
                            new Student { Roll_num = 3, Name = "Dina", Marks = 87 },
                            new Student { Roll_num = 4, Name = "Leen", Marks = 43 },
                            new Student { Roll_num = 5, Name = "Krish", Marks = 57 } };
}

After creating the list, suppose we need to select the students with marks greater than 60 and display that to the user. For that, we will use lambda expressions and LINQ queries.

Console.WriteLine("Through Lambda Expression");
IEnumerable<Student> sortedData = students.Where(x => x.Marks > 60);
foreach (var s in sortedData) Console.WriteLine(s.Roll_num + "  " + s.Name + "  " + s.Marks);

Console.WriteLine("Through LINQ query");
IEnumerable<Student> result = from s in students
    where s.Marks> 60 select s; foreach (var s in sortedData) Console.WriteLine(s.Roll_num + "  " + s.Name + "  " + s.Marks);

Note that in the above code segment, we have selected the same data in 2 different ways. See that through Lambda statements, querying data is very simple and requires less coding than LINQ queries.

The output will be the same for both cases:

Output of LINQ vs Lambda Expression

In the previous example, we displayed all the data of the students. If we need to get the name of such students who have scored marks greater than 60, then the lambda expression will be:

var stuNames = students.Where(x => x.Marks > 60).Select(x => x.Name);
foreach (var s in stuNames) Console.WriteLine(s);

This will return only the names of the students. Therefore, we have not stored them in an IEnumerable type.

The output will be:

Output of Lambda Expression 1

Suppose we want the students’ names and marks, but first, we need to sort them based on their marks. We will use the OrderBy function to sort the data.

var stuNames = students.OrderBy(x => x.Marks).Select(x => new { x.Name, x.Marks });
foreach (var s in stuNames) Console.WriteLine(s.Name + "  " + s.Marks);

The output will be:

Output of Lambda Expression 2

Thus, we can see that different methods can query data using lambda expressions. Lambda expressions are helpful when you have huge data and require minimal coding steps to query or apply various operations to the data.

Related Article - Csharp LINQ