Lambda Expressions

Anonymous Methods

The idea behind anonymous methods it to write methods inline to the code so you don't have to go through the trouble of declaring a formal named method. They are mainly used for small methods that don't require any need for reuse.

Instead of declaring a separate method IsAvailable to find an employee in a list of strings:

class Employee

{

    static void Main(string[] args)

    {

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

        Emp.Add(“Shriya”);

        Emp.Add(“Phaniswara”);

        Emp.Add(“NAGAVALLI”);

        Emp.Add(“Deepika”);

        Emp.Add(“Nair”);

        string strEmp = Emp.Find(IsAvailable);

        Console.WriteLine(strEmp);

    }

    public static bool IsAvailable(string name)

    {

    return name.Equals(“NAGAVALLI”);

    }

}

You can declare an anonymous method inline

 

class Employee

{

    static void Main(string[] args)

    {

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

        Emp.Add(“Shriya”);

        Emp.Add(“Phaniswara”);

        Emp.Add(“NAGAVALLI”);

        Emp.Add(“Deepika”);

        Emp.Add(“Nair”);

        String strEmp = Emp.Find(delegate(string name)

            {

                return name.Equals("Nair");

            });

        Console.WriteLine(strEmp);

    }

}

 

Lambda Expressions

Lambda Expressions make things even easier by allowing you to avoid the anonymous method

string strEmp = Emp.Find((string name)

                          => Emp.Equals("Deepika"));

Console.WriteLine(strEmp);

 

Or you can simply use :

 

string strEmp = Emp.Find(n => n.Equals("Deepika"));

        Console.WriteLine(strEmp);

Ebook Download
View all
Learn
View all