Many of the Lambda expressions samples demonstrate Selects and Order By but I recently discovered the ability of Lambda expressions to be used as delegate methods. You can use Func<T> for methods that return a result which provides a very concise shorthand notation. In addition to Func<T> you can use Action<T> and Predicate<T>
Here is an example that uses Func<T,TResult> to add two numbers together
// Lambda Function that adds two numbers
Func<int, int, int> add = (int val1, int val2) => val1 + val2;
// add 200 and 100
Console.WriteLine(add(200, 100));
In this case the Func<int, int,int> indicates that the method takes two integers and returns an integer.
Action<T> allows you to capture behavior:
// Action<T> to echo input
Action<string> echo = (s) => Console.WriteLine(s);
// invoke echo
echo("Hello");
Predicate<T> allows you to filter:
// Create fibonacci sequence
List<int> fi = new List<int>();
fi.AddRange(new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 });
// select the matches
Predicate<int> matches = num => num % 2 == 1;
var odd = fi.FindAll(matches);
// use array Foreach<T> to display the results
Array.ForEach<int>(odd.ToArray(),x=>Console.WriteLine(x));
In the example above I use Array.ForEach<T> to display the results instead of a foreach loop.
You can download the sample code here.
No comments:
Post a Comment