IEnumerable<Customer> rsCustomer = objCustomerList.Where(p => p.Fullname == "John Olamendy");
Listing 11
This expression is semantically equivalent to anonymous methods following the rule params=>expression. That is, the p is parameter of the anonymous method referencing to every instance of Customer in the collection. In this case, we don't need to declare the parameter type because it's inferred by the compiler from the types in the collections. The expression is normal C# statement that, in this case, returns a Boolean value. Let's re-write the previous lambda expression into an anonymous method (see Listing 12).
IEnumerable<Customer> rsCustomer = objCustomerList.Where
(
delegate(Customer objTemp)
{
return objTemp.Fullname == "John Olamendy";
}
);
Listing 12
I would like to illustrate the evolution from delegates (in early C# language), through anonymous methods (in C# 2.0) to lambda expression (in C# 3.0) using an example taking from the Visual Stduio 2008 documentation (see Listing 13).
class Test
{
delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
// Original delegate syntax required
// initialization with a named method.
TestDelegate testdelA = new TestDelegate(M);
// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };
// Invoke the delegates.
testdelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Hello. My name is M and I write lines.
That's nothing. I'm anonymous and
I'm a famous author.
Press any key to exit.
*/
Listing 13