How to use lambda expressions in C#

Take advantage of lambda expressions in C# to add flexibility and power to the anonymous methods in your application

How to use lambda expressions in C#
Monsitj / Getty Images

Lambda expressions were first introduced in .NET 3.5, at the same time that Language Integrated Query (LINQ) was made available. Lambda expressions are like anonymous methods but with much more flexibility. When using a lambda expression, you don't need to specify the type of the input. Hence, a lambda expression provides a shorter and cleaner way of representing anonymous methods.

In this article, we’ll look at how we can use lambda expressions in C#. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

Following these steps should result in a new .NET Core console application project in Visual Studio 2019. We’ll use this project to work with C# lambda expressions in the subsequent sections of this article.

Anatomy of a Lambda expression

Essentially a lambda expression is a method that doesn’t have a declaration. In other words, a lambda expression is a method that doesn’t have an access specifier or a name. A lambda expression can be divided into two sections — the left part and the right part. The left part is used for input, and the right part is used for writing expressions.

Here is the syntax for using lambda expressions in C#.

(Input parameters) => Expression or statement block

You can have two types of lambda expressions, an expression lambda and a statement lambda. An expression lambda is comprised of an input on the left side and an expression on the right side, as shown below.

input => expression;

A statement lambda is comprised of an input on the left side and a set of statements on the right side, as shown below.

input => { statements };

Lambda expression examples in C#

Writing a lambda expression is simple — you just need to remove the delegate keyword and parameter type from an anonymous method. Consider the following anonymous method that uses the delegate keyword as well as a parameter type.

delegate(Author a) { return a.IsActive && a.NoOfBooksAuthored > 10; }

The above statement can be converted to a lambda expression as shown in the code snippet given below.

(a) => { a.IsActive && a.NoOfBooksAuthored > 10; }

In the above statement a is the parameter and => is the lambda operator. The following statement is the expression.

a.IsActive && a.NoOfBooksAuthored > 10;

Here is another example of a lambda expression that displays the odd numbers between 1 and 9 at the console window.

List<int> integers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach(int num in integers.Where(n => n % 2 == 1).ToList())
{
  Console.WriteLine(num);
}

Lambda expressions with and without parameters

Lambda expressions can be parameterless or have one or more parameters. The following code snippet illustrates a lambda expression that doesn’t have any parameters.

() => Console.WriteLine("This is a lambda expression without any parameter");

Lambda expressions can also have one or more parameters. The following code snippet illustrates how you can pass one parameter to a lambda expression.

(a, numberOfBooksAuthored) => a.NoOfBooksAuthored >= numberOfBooksAuthored;

You can also specify the type of the parameter in a lambda expression, as shown in the code snippet given below.

(a, int numberOfBooksAuthored) => a.NoOfBooksAuthored >= numberOfBooksAuthored;

You can even specify multiple statements in a lambda expression using curly braces. This is shown in the following code snippet. 

(a, 10) =>
{
   Console.WriteLine("This is an example of a lambda expression
                      with multiple statements");
   return a.NoOfBooksAuthored >= 10;
}

Statement lambdas in C#

A statement lambda uses a syntax identical to expression lambdas. The difference is that, instead of having an expression to the right of the operator, the statement lambda has a code block that includes one or more statements.

The following code snippet illustrates how you can take advantage of a statement lambda to display the even numbers between 1 and 9 at the console window.

int[] integers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in integers.Where(x =>
{
   if (x % 2 == 0)
         return true;
    return false;
 }
 ))
Console.WriteLine(i);

Lambda expressions are a great feature in .NET and .NET Core that provide a shorter way of representing anonymous methods. Lambda expressions can have zero parameters or one or more. You can even assign lambda expressions to Func, Action, or Predicate delegates. In a future article here, we’ll explore these and other features of lambda expressions. We’ll also explore how we can work with lambda expressions and LINQ as well as async lambdas.

How to do more in C#:

Copyright © 2020 IDG Communications, Inc.