Lambda Expressions in C#


Lambda expressions reduce the amount of code required to define a method. For example let’s create simple program to find whether particular name is there in the list or not as shown below.

Open Microsoft Visual Studio 2013 => Create simple program as shown below to find name in the list.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace LambdaExpressionsExp

{

    class Program

    {

        static void Main(string[] args)

        {

            List<string> listNames = new List<string>();

 

            listNames.Add("Bob");

            listNames.Add("Smith");

            listNames.Add("Raj");

            listNames.Add("Oscar");

            listNames.Add("Jason");

 

            string name = listNames.Find(IsRaj);

        }

 

        static bool IsRaj(string sName)

        {

            return (sName == "Raj");

        }

    }

}

 

As shown above we are finding whether name “Raj” is there or not in the list by creating the new method IsRaj(). Instead of creating the new method we can reduce the amount of code through lambda expressions as shown below.

using System.Collections.Generic;

 

namespace LambdaExpressionsExp

{

    class Program

    {

        static void Main(string[] args)

        {

            List<string> listNames = new List<string>();

 

            listNames.Add("Bob");

            listNames.Add("Smith");

            listNames.Add("Raj");

            listNames.Add("Oscar");

            listNames.Add("Jason");

 

            string name = listNames.Find(sName => sName == "Raj");

        }

    }

}

 

In the above code we are using sName => sName == "Raj" lambda expression code instead of creating new method IsRaj(), this reduces the amount of code. Lambda expression uses the => operator to separate a list of method parameters from the method body. The compiler (usually) can infer the data types of the parameters.