January 09, 2009

Example: foreach, Predicate, Anonymous, Lambda

Following example demonstrates various ways to evaluate function using traditional foreach, predicate delegate, anonymous method and lambda expression.

Anonymous methods are introduced in C# 2.0 where as Lambda expressions in C# 3.0.

class Program
{
static void Main(string[] args)
{
List<string> products = new List<string>();
products.Add("HDTV");
products.Add("UniRemote");
products.Add("BDPlayer");
products.Add("AvReceiver");

string strResult;

// old for each
foreach (string pro in products)
{
if (pro.Equals("AvReceiver"))
Console.WriteLine(pro);
}

// using Predicate delegate
strResult = products.Find(IsAV);
Console.WriteLine(strResult);

// using Anonymous method
strResult = products.Find(delegate(string name)
{
return name.Equals("AvReceiver");
});
Console.WriteLine(strResult);

// using lambda expression
strResult = products.Find(name => name.Equals("AvReceiver"));
Console.WriteLine(strResult);

}
public static bool IsAV(string pro)
{
return pro.Equals("AvReceiver");
}

}