Definition and Use of Lambda Expressions in C# .Net
Lambda Expressions |
delegate int Increment(int v);
// Declare a delegate that takes an int argument
// and returns a bool result.
delegate bool IsEven(int v);
class SimpleLambdaDemo
{
static void Main()
{
// Create an oIncrement delegate instance that refers to
// a lambda expression that increases its parameter by 2.
Increment oIncrement = count => count + 2;
// Now, use the oIncrement lambda expression.
Console.WriteLine("Use oIncrement lambda expression: ");
int iIndex = -10;
while(iIndex <= 0)
{
Console.Write(iIndex + " ");
iIndex = oIncrement(iIndex); // increase x by 2
}
Console.WriteLine("\n");
// Create an IsEven delegate instance that refers to
// a lambda expression that returns true if its parameter
// is even and false otherwise.
IsEven oIsEven = n => n % 2 == 0;
// Now, use the oIsEven lambda expression.
Console.WriteLine("Use oIsEven lambda expression: ");
for(int i = 1; i <= 10; i++)
{
if(oIsEven(i)) Console.WriteLine(i + " is even.");
}
}
}
The output is shown here:
Use oIncrement lambda expression:
-10 -8 -6 -4 -2 0
Use oIsEven lambda expression:
2 is even.
4 is even.
6 is even.
8 is even.
10 is even.
// and returns a bool result.
delegate bool IsEven(int v);
class SimpleLambdaDemo
{
static void Main()
{
// Create an oIncrement delegate instance that refers to
// a lambda expression that increases its parameter by 2.
Increment oIncrement = count => count + 2;
// Now, use the oIncrement lambda expression.
Console.WriteLine("Use oIncrement lambda expression: ");
int iIndex = -10;
while(iIndex <= 0)
{
Console.Write(iIndex + " ");
iIndex = oIncrement(iIndex); // increase x by 2
}
Console.WriteLine("\n");
// Create an IsEven delegate instance that refers to
// a lambda expression that returns true if its parameter
// is even and false otherwise.
IsEven oIsEven = n => n % 2 == 0;
// Now, use the oIsEven lambda expression.
Console.WriteLine("Use oIsEven lambda expression: ");
for(int i = 1; i <= 10; i++)
{
if(oIsEven(i)) Console.WriteLine(i + " is even.");
}
}
}
The output is shown here:
Use oIncrement lambda expression:
-10 -8 -6 -4 -2 0
Use oIsEven lambda expression:
2 is even.
4 is even.
6 is even.
8 is even.
10 is even.