joydip_kanjilal
Contributor

How to use lambda expressions in C#

how-to
Jan 27, 20206 mins
C#Microsoft .NETSoftware Development

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

Java  >  Lambda expressions  >  Lambda symbol / abstract formulas / binary code
Credit: 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#:

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author