Tutorial by Examples

List<int> l2 = l1.FindAll(x => x > 6); Here x => x > 6 is a lambda expression acting as a predicate that makes sure that only elements above 6 are returned.
public delegate int ModifyInt(int input); ModifyInt multiplyByTwo = x => x * 2; The above Lambda expression syntax is equivalent to the following verbose code: public delegate int ModifyInt(int input); ModifyInt multiplyByTwo = delegate(int x){ return x * 2; };
Typically lambdas are used for defining simple functions (generally in the context of a linq expression): var incremented = myEnumerable.Select(x => x + 1); Here the return is implicit. However, it is also possible to pass actions as lambdas: myObservable.Do(x => Console.WriteLine(x)); ...
Use parentheses around the expression to the left of the => operator to indicate multiple parameters. delegate int ModifyInt(int input1, int input2); ModifyInt multiplyTwoInts = (x,y) => x * y; Similarly, an empty set of parentheses indicates that the function does not accept parameters. ...
Unlike an expression lambda, a statement lambda can contain multiple statements separated by semicolons. delegate void ModifyInt(int input); ModifyInt addOneAndTellMe = x => { int result = x + 1; Console.WriteLine(result); }; Note that the statements are enclosed in braces {}. ...
Assuming the following Person class: public class Person { public string Name { get; set; } public int Age { get; set; } } The following lambda: p => p.Age > 18 Can be passed as an argument to both methods: public void AsFunc(Func<Person, bool> func) public void AsE...
Lambda expressions can be used to handle events, which is useful when: The handler is short. The handler never needs to be unsubscribed. A good situation in which a lambda event handler might be used is given below: smtpClient.SendCompleted += (sender, args) => Console.WriteLine("Ema...

Page 1 of 1