Mary Had a Little LAMBda

C# 19 August 2011 | 0 Comments

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read “x goes to x times x.”
http://msdn.microsoft.com/en-us/library/bb397687.aspx
Let’s sum up the jargon. Lambda expressions are basically just Functions/Methods.
Let’s look at some code that could choose all the odd numbers in an array:
int[] arrayNumbers = new[] { 103, 88, 13, 16, 166, 117, 999, 22, 4, 9, 1 };

foreach (int i in arrayNumbers.Where(x => (x % 2) > 0))
//% = modulo or mod. % 2 returns 0 if even 1 if odd.
Console.WriteLine(i);
//results 103 13 117 999 9 1

Simple and clear. The power is in its readability. There is no need to track down another method to see what happens to the variables value. It’s all right there.

Tagged in , , , , , ,

Leave a Reply