using System; class Test { static void Main() { Func<int, int> square = x => x * x; Console.WriteLine(square(3)); // 9 } }
A lambda expression can reference the local variables and parameters of the method in which it's defined.
using System; delegate int NumericSequence(); class Test { static void Main() { int seed = 0; NumericSequence natural = () => seed++; Console.WriteLine(natural()); Console.WriteLine(natural()); } }
Last Prototype
using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass { public static void Main() { string[] presidents = {"G", "H", "a", "H", "over", "Jack"}; string name = presidents.Last(); Console.WriteLine(name); } }
Last with string operator
using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass { public static void Main() { string[] presidents = {"G", "H", "a", "H", "over", "Jack"}; string name = presidents.Last(p => p.StartsWith("H")); Console.WriteLine(name); } }
Use LastOrDefault
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; public class MainClass{ public static void Main(){ int[] numbers = { 1, 3, 5, 7, 9 }; var query = numbers.FirstOrDefault(n => n % 2 == 0); Console.WriteLine("The first even element in the sequence"); Console.Write(query); Console.WriteLine("The last odd element in the sequence"); query = numbers.LastOrDefault(n => n % 2 == 1); Console.Write(query); } }
A local variable instantiated within a lambda expression is unique per invocation of the delegate instance.
using System; delegate int NumericSequence(); class Test { static NumericSequence Natural() { return () => { int seed = 0; return seed++; }; } static void Main() { NumericSequence natural = Natural(); Console.WriteLine(natural()); Console.WriteLine(natural()); } }
square is assigned the lambda expression x = > x * x:
using System; delegate int Transformer(int i); class Test { static void Main() { Transformer square = x => x * x; Console.WriteLine(square(3)); // 9 } }