2. Why Lambda Expressions? Lambda expressions are simply methods; Give a shorter form of a methods; Speed up our work.
3. Using a Delegate public delegate int Arithmetic(int x); static public int Square(int x) { return x * x; } Arithmetic myOperation= new Arithmetic (Square); Console.WriteLine("{0}", myOperation(5));
4. Using an Anonymous Methods public delegate int Arithmetic(int x); Arithmetic myOperation= new Arithmetic ( delegate { return x * x; }); Console.WriteLine("{0}", myOperation(5));
6. Using λ with Two Arguments public delegate int Mul(int x, int y); MulmyOperation= (x, y) => x * y; Console.WriteLine("{0}", myOperation(5, 6)); //Also with explicit input type MulmyOperation = (int x, int y) => x * y; Console.WriteLine("{0}", myOperation(5, 6));
7. Using λ with Zero Arguments public delegate long Ticks(); Ticks myOperation= () => DateTime.Now.Ticks; Console.WriteLine("{0}", myOperation());
9. int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where( x => { if (x % 2 == 0) return true; else if (x >= 7) return true; return false; } )) Console.WriteLine(i); Complex body
10. How to pronounce If λ is a predicate x => x == “Predicate” => spoken as “such that” Ex. x such that x state equals Predicate If λ is a projection returns a new type x => newSomeObject(x) => Spoken as “becomes” Ex. x becomes new some object with name x.
11. The Func Delegate Types public delegate TR Func<TR>(); public delegate TR Func<T0, TR>(T0 a0); public delegate TR Func<T0, T1, TR>(T0 a0, T1 a1); public delegate TR Func<T0, T1, T2, TR>(T0 a0, T1 a1, T2 a2); public delegate TR Func<T0, T1, T2, T3, TR>(T0 a0, T1 a1, T2 a2, T3 a3); publicList<T> FilterList<T>( List<T> source, Func<T, bool> filter ) { List<T> list = new List<T>(); foreach( T l in source ) { if ( filter( l ) ) list.Add( l ); } return list; } List<int> list = new List<int>() { 3, 5, 7, 9, 5 }; List<int> filteredList = FilterList<int>( list, x => x > 5 );
12. The Action Delegate Types public delegate voidAction(); public delegate voidAction<T0>(T0 a0); public delegate voidAction<T0, T1>(T0 a0, T1 a1); public delegate voidAction<T0, T1, T2>(T0 a0, T1 a1, T2 a2); Public delegate voidAction<T0, T1, T2, T3>(T0 a0, T1 a1, T2 a2, T3 a3); void DoSomethingWithDelay(Action execute) { Thread.Sleep(1000); execute(); } void F() {DoSomethingWithDelay( () => { Console.WriteLine("Done"); } ); }