Lambda expressions provide a concise syntax for writing anonymous
methods. The C# 3.0 specification describes lambda expressions as a
super set of anonymous methods.
In C# 2.0, you can write a delegate using an anonymous method, as
shown in this example:
public delegate int MyDelegate(int n); class MyClass { static void Main() { // Anonymous method that returns the argument multiplied by 5: MyDelegate delegObject1 = new MyDelegate( delegate(int n) { return n * 5; } ); // Display the result: Console.WriteLine("The value is: {0}", delegObject1(5)); } }This program outputs the value 25.
Using a lambda expression you can use a simpler syntax to achieve the
same goal:
MyDelegate delegObject2 = (int n) => n * 5;
using System; using System.Collections.Generic; using System.Text; using System.Query; using System.Xml.XLinq; using System.Data.DLinq; namespace Lambda { public delegate int MyDelegate(int n); class MyClass { static void Main() { MyDelegate delegObject1 = new MyDelegate( delegate(int n) { return n * 5; } ); Console.WriteLine("The value using an anonymous method is: {0}", delegObject1(5)); MyDelegate delegObject2 = (int n) => n * 5; Console.WriteLine("The value using a lambda expression is: {0}", delegObject2(5)); Console.ReadLine(); } } }Output:
The value using an anonymous method is: 25
The value using a lambda expression is: 25
A lambda expression can use two arguments, especially when you are
using the Standard Query Operators. Let us start by declaring the following
delegate that uses two arguments:
public delegate int MyDelegate(int m, int n);
You can instantiate the delegate by using a lambda expression like this:
MyDelegate myDelegate = (x, y) => x * y;
You can then invoke the delegate and display the result as follows:
Console.WriteLine("The product is: {0}", myDelegate(5, 4));
// output: 20