Lambda Expressions


Lambda Expressions allow us to write functions that can be passed as arguments to methods.

Lambda Expressions is an evolution of anonymous methods that provide improved type inference and conversions to both delegate types and expression trees.

All Lambda Expressions use the lambda operator =>, which is read as "goes to". The left side of the Lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.

Lambda Expressions are used in method-based LINQ queries as arguments to standard query operator methods.

Code Example

This code sample specifies a Lambda Expression to search a Generic List collection.

class Program { public static List<Route> listRoutes = new List<Route>();
static void Main(string[] args) { listRoutes.Add(new Route("A", "B", 5)); listRoutes.Add(new Route("A", "C", 2)); listRoutes.Add(new Route("A", "D", 7)); listRoutes.Add(new Route("B", "D", 4));
Route findRoute = null; findRoute = FindRoute("A", "B"); if (findRoute != null) { Console.WriteLine("Distance from A to B: {0}", findRoute.Distance.ToString()); } findRoute = null; Console.Read(); } private static Route FindRoute(String Start, String End) { return listRoutes.Find(r => (r.Start == Start) && (r.End == End)); } } class Route { public String Start { get; set; } public String End { get; set; } public UInt16 Distance { get; set; }
public Route(String Start, String End, UInt16 Distance) { this.Start = Start; this.End = End; this.Distance = Distance; } }