Monday, January 11, 2010

Use lambda

Lambda expressions use the lambda operator =>, which is read as "goes to".
(input parameters) => expression
The => operator has the same precedence as assignment (=) and is right-associative.

Example
 int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);

Lamda Expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true;
lambda expressions can be converted to expression trees which allows
for a lot of the magic that LINQ to SQL.

The following is an example using anonymous delegates then lambda expressions.

==Delegate==

delegate(int x)
{
return (x % 2) == 0;
}
==Lambda==
(x => (x % 2) == 0)


No comments:

Post a Comment