Tuesday, March 12, 2013

C# Delegate, Func, Action, and Extension Method

IEnumerable<string> cities = new[]{"Falls Church", "Annandale", "Reston"};
//delegate 1
IEnumerable<string> query = cities.Filter(StringThatStartWithA);
//delegate 2
IEnumerable<string> query2 = cities.Filter(delegate(string item)
           {
            return item.StartsWith("A");
           });
         
//expression method
IEnumerable<string> query3 = cities.Filter((item) => item.StartsWith("A"));
static bool StringThatStartWithA(string s)
{
 return s.StartWith("A");
}
public static IEnumerable<T> Filter<T> (this IEnumerable<T> input, FilterDelegate<T> predicate)
{
 foreach(var item in input)
 {
  if(predicate(item))
  {
   yield return item;
  }
 }
}
//or, FilterDelegate<T> predicate can be replaced by Func<T, bool> predicate
//Func returns a value while Action does not
//ex:
//Func<int, int> square = x => x*x;
//Func<int, int, int> add = (x,y) => x+y;
//Action<int> write = x => Console.WriteLine(x);
//write(square(add(1,3)));

public delegate bool FilterDelegate<T>(T item);

No comments: