This post has been sitting in my drafts for months! Because my friend Phil just posted his post on Lambda Expressions I'll simply link to his post and present the rest of this as supplemental examples.
// Delegates
// My Blog Engine is having trouble showing these so there may be some extra spaces
public delegate IntMathExpression (int x, int y);
public delegate IntMathExpressionSingle (int x);
public delegate FloatMathExpression (float x, float y);
// Basic Lamda Expression
IntMathExpression a = (int x, int y) => x * y;
IntMathExpression b = (int alpha, int brovo) => alpha * brovo;
IntMathExpressionSingle c = (int x) => x * x;
// "such that" =>
// Parameters => function body
// (param1, param2) => param1 + param2
// Lamda Expression using Type Inference
FloatMathExpression d = (x, y) => x + 3.14f * y;
// There is usually no need for custom delegates
Func<float, float, float> e = (x, y) => x * 100.0f + y;
// Example using a lamda expression
List<int> primes = new List<int>() { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 };
var p = primes.Where( prime => prime.ToString().EndsWith( "3" ) );
// Deferred Execution
foreach (int i in p) {
MessageBox.Show(i.ToString());
}
// Query Expression Format
var p2 = from prime in primes
where prime.ToString().EndsWith("3")
select prime;
List<int> results = p2.ToList();
// Lamda Expressions mixed with Extension Methods
List<string> str = new List<string>() { "The Lord of the Rings", "Star Wars, Eposode III", "Ratatouille" };
var p3 = from movie in str
where movie.CountVowels() > 5
select movie;
List<string> movieResults = p3.ToList();