Sunday, August 29, 2010

LAMBDA EXPRESSIONS

Lambda expressions can be summarized in one sentence as simply functions/methods.A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

The basic form for a lambda expression is:

a) argument-list => expression

b)syntax of () => { /* body of void function here */ }; //void delegate.

Examples:-

Example1

To show lambda expressions in context, consider the problem where you have an array with 10 digits in it, and you want to filter for all digits greater than 5. In this case, you can use the Where extension method, passing a lambda expression as an argument to the Where method:

int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };

foreach (int i in source.Where(x => x > 5))
Console.WriteLine(i);

Example2-LAMBDA with 2 Arguments




// Defines a delegate that takes two ints and returns an int
public delegate int MultiplyInts(int arg, int arg2);

You can declare and initialize a delegate:

MultiplyInts myDelegate = (a, b) => a * b;
Console.WriteLine("{0}", myDelegate(5, 2));

//gets the first number smaller than 10 in the list
int result=numbers.Find( n=> n<10);

//anonymous method
numbers.Sort(delegate(int x, int y){ return y-x; });

//lambda expression
numbers.Sort((x,y)=> y-x);

Example 3 -Multiple Statements

The code used in a lambda doesn't have to be a single statement. You can include multiple statements if you enclose them inside a statement block:


Action action=
control=>
{
control.ForeColor=Color.DarkRed;
control.BackColor=Color.MistyRose;
});

No comments: