BITE SIZE C# – LAMBDA EXPRESSIONS

A lambda expression is a function definition with no name, no access modifier and no return statement. Lambda expressions are also known as Anonymous methods or functions.

The syntax for the definition of a lambda expressions is as follows:

(arguments) => expression

The below C# code does not use lambda expressions and is given as a comparative reference point:

static int SquareNumber(int number)
{
   return number*number;
}

static void Main(string[] args)
{
   Int y = SquareNumber(10);
   Console.WriteLine(y); // This will display 100
}

The above code can be refactored using a lambda expression as follows:

static void Main(string[] args)
{

   Func<int,int> square = number=>number*number;
   Console.WriteLine(square(10)); // This will display 100

}

The result of this refactor is fewer lines of code in order to achieve the same result.

Lambda expressions can also make use of Delegates as shows here:

delegate int squareDelegate (int number);

static void Main(string[] args)
{
   squareDelegate square = number=>number*number;
   Console.WriteLine(square(10)); // This will display 100
}

 

The syntax for a lambda expression that takes no arguments is as follows:

()=>expression

For one argument:

X=>expression

For more than one argument:

(x,y,z)=>expression

 

Lambda expressions can also be very effectively used with objects that implement the IEnumerable and IQueryable interfaces to filter or search based on defined criteria, for example:

var highPriceList = PriceList.FindAll(a=>a.Price>10);

This will return all items with a price larger than 10, and place these items in the highPriceList.

 

var nyCustomers = Customers.Where(a=>a.City==”New York”);

This will place all customers with the city property set to “New York” into the nyCustomers collections.

Lambda expressions are an extremely useful tool with many other uses.

BITE SIZE C# – LAMBDA EXPRESSIONS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s