Programming - C# Anonymous methods and Lambda
Up until now, we have relied on defined delegates and anoymous delegates to do the brunt of work when it comes to isolated code blocks which are repetitive but localised to a method. But with C# 3.0, we are provided with Lambda expressions aswell.
A quick example of 2 functions, 1 using anonymous methods and another using Lambda are provided below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;
namespace Example
{
public delegate bool KeyValueFilter<K, V>(K key, V value);
static class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("AA");
list.Add("ABC");
list.Add("DEFG");
list.Add("XYZ");
Console.WriteLine("Anon Test");
AnonMethod(list);
Console.WriteLine("Lambda Test");
LambdaExample(list);
Dictionary<string, int> varClothes= new Dictionary<string,int>();
varClothes.Add("Jeans", 20);
varClothes.Add("Shirts", 15);
varClothes.Add("Pajamas", 9);
varClothes.Add("Shoes", 9);
var ClothesListShortage = varClothes.FilterBy((string name,
int count) => name == "Shoes" && count < 10);
// example of multiple parameters
if(ClothesListShortage.Count > 0)
Console.WriteLine("We are short of shoes");
Console.ReadLine();
}
static void AnonMethod(List<string> list)
{
List<string> evenNumbers =
list.FindAll(delegate(string i)
{ return (i.Length % 2) == 0; });
foreach (string evenNumber in evenNumbers)
{
Console.WriteLine(evenNumber);
}
}
static void LambdaExample(List<string> list)
{
var evenNumbers = list.FindAll(i => (i.Length % 2) == 0);
// example of single parameter
foreach(string i in evenNumbers)
{
Console.WriteLine(i);
}
}
}
public static class Extensions
{
public static Dictionary<K, V> FilterBy<K, V>(this Dictionary<K, V> items, KeyValueFilter<K, V> filter)
{
var result = new Dictionary<K, V>();
foreach(KeyValuePair<K, V> element in items)
{
if (filter(element.Key, element.Value))
result.Add(element.Key, element.Value);
}
return result;
}
}
}
Lamda provides a more structured implementation of anonymous localised code blocks.