creativity in code.

creativity is that spark of electricity before an explosion.
it allows us, in a single instance to explore all possibilities without hesitation.

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.


Other pages of interest:
[+] Microsoft DLR (Dynamic Language Runtime) information released
[+] Java and .NET both bring something to the Enterprise arena
[+] Enterprise Java performance tuning tips
[+] Java and .NET both bring something to the Enterprise arena
[+] Programming - Facade Structural Design Pattern
[+] Java EE and Java SE


Comments(1)

Posted by Hello! cialis , on 11/5/2009 5:44:35 PM
Hello! cialis ,

add comment Add Comment

Add your comment

Email address:
Your name:
Do you want your email to be visible?: