anyway let's take a look at a predicate example; a predicate is also a Func that takes in one parameter and returns either true or false as a result.
static void Main(string[] args)
{
var nums = Enumerable.Range(0, 10);
Predicate<int>
getOdd = n => n % 2 == 1;
var result1 = Array.FindAll(nums.ToArray<int>(), getOdd);
Console.WriteLine(result1.Length);
var result2 = nums.Count(getOdd.Invoke);
Console.WriteLine(result2);
}
static void Main(string[] args)
{
Action<string>
SayHello = name => Console.WriteLine($"Hello {name}");
SayHello("Pawel");
}
static void Main(string[] args)
{
Action<string>
SayHello = name =>
{
string output = $"Hello {name}";
Console.WriteLine(output);
};
SayHello("Pawel");
}
Making it a statement lambda. A statement lambda can also have a return type
static void Main(string[] args)
{
Func<int, bool> IsOdd = n =>
{
if (n % 2 == 1)
return true;
return false;
};
int result = Enumerable.Range(0, 10).Count(IsOdd);
Console.WriteLine($"Odd number count:{result}");
}
Creating an async Lambda is also very straight forward, just leverage the async/await keywords.
static void Main(string[] args)
{
var nums = Enumerable.Range(0, 10);
Func<int, Task<bool>> IsOdd = async n =>
{
await Task.Delay(500);
if (n % 2 == 1)
return true;
return false;
};
foreach (var num in nums)
{
var isOdd = IsOdd(num).Result;
Console.WriteLine("{0} {1}", num, isOdd ? "is odd" : "is even");
}
}
Lambda Expressions are a shorthand syntax for creating anonymous methods.
using System;
using System.Linq;
namespace pc.LambdaExpression
{
class Program
{
static void Main(string[] args)
{
var ints = Enumerable.Range(0, 10).ToArray();
var odds = Array.FindAll(ints, i => i % 2 == 1);
Console.WriteLine("Show odd integers");
foreach (var n in odds)
Console.Write($"{n} ");
}
}
}
The => is referred to as the "goes to" operator.