Basically these are Anonymous delegates crunched upto one line of code.
The fully documented code is here .
Remember to keep the fully documented code open/visible to understand the explaination below.
A brief primer on Lambda expressions follows:
Lambda expressions are available with .NET 3.5.
Apart from making the code more readable we can mix it with other .NET features
like generics and anonymous methods.
Lambda expressions are confusing at the first look but understanding them is the code to
writing real chiq LINQ Code, be it LINQ to SQL or LINQ to XML.
What is a Lambda Expression?
In simple words it is a shortcut to Anonymous methods/delegates.
Anonymous Methods and Standard methods?
Standard methods are defined in code, given a unique name with predefined parameter and
later called from somewhere else.
Anonymous functions are defined inplace and the easiest method to identify a Lambda expression
is the presence of '=>' operator.
To the left of the => will be the parameter list and on the right side will be the
expression to be evaluated.
Lambda expressions define a function's parameters and its body.
It has the limitation that the body must be a single expression which returns a single object.
They can be used anywhere a delegate would be used. They are callback methods.
Let me show you an example of a call back with a delegate
1.Define a delegate signature
public delegate int CallBackFunction(int x, int y);
2.Declare function matching signature as delegate
static int MultiplyNumbers(int x, int y)
{
return x * y;
}
3. Any code that calls this method must pass a callback of the callBack delegate type.
protected int CalculateProduct(IEnumerable
{
int result = 0;
foreach (int value in values)
result callback(result, value);
return result;
}
The same code can be called using Anonymous Function without using a reference to MultiplyNumbers() as
product = CalculateProduct(numbers, delegate(int x, int y)
{
return x * y;
}
);
This tells the compiler that the parameter list and the method body follows.
ie. the inline function delegate(int x, int y)
{
return x * y;
}
delegate (int x, int y) is the parameter list which in Lambda equals (int x,int y)
Hence in Lambda expression (int x,int y) => which will for the left hand side of the expression.
The right hand side of the expression ie. the predicate will form the result ie x * y
Hence the function
product = CalculateProduct(numbers, delegate(int x, int y)
{
return x * y;
}
);
when written in lambda will be
product = CalculateProduct(numbers, (x,y)=>x*y);
I would really suggest you to try out a few examples and get used to the Lambda syntax as it
is really a very cool feature and you just cannot miss having it in your programming skill armoury.
No comments:
Post a Comment