One of the new things that came new with c# 3.0 is lambda expressions. I started to read about them yesterday (yes, shame on me but i was busy ok ??!). It isnt easy to understand the expressions, but while i was reading the apress pro linq book, at chapter 2, i saw a good example :) that i want to share.
Let's say we have a function that accepts an array of integers, and a filter function. It will appy the filter to the array, and returns the integers that passes the filter. The sample function could be something like this:
public static List<int> FilterArrayOfInts(int[] ints, IntFilter filter)
{
List<int> arrInts= new List<int>();
foreach (int i in arrInts)
if (filter(i))
arrInts.Add(i);
return arrInts;
}
So now, if we want to have a filter so that, our function returns only the odd numbers, we could write a function like below:
public static bool IsOdd(int i)
{
return ((i & 1) == 1);
}
We can easily define a delegate function such as :
public delegate bool IntFilter(int i);
This delegate function can point to functions that takes an integer as a parameter and returns bool. So if want to use this in our main function, we can have a code like this :
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> oddNums = FilterArrayOfInts(nums, IsOdd);
What we've done is, we passed our IsOdd function as a filter function to get the odd numbers. This is old classical way :). Now with C# 2.0, we have anonymous delegates, which might help our problem. Anonymous delegate are inline functions that dont have a name and they are defined at the point they are called. Of course one drawback is you can't reuse the anonymous delegates without our evil-devil copy-paste habit. But in this scenario, i dont think that IsOdd is a reusable function so i will rewrite this using anonymous delegate. So lets do this :)
List<int> oddNums2= FilterArrayOfInts(nums, delegate(int i) { return ((i & 1) == 1); });
As you can see above, instead of passing a predefined function as a parameter, we created an anonymous delegate right at the point we need it, and it still returns a bool, and takes an int as a parameter. Simple heh ?!
Last step is using lambda expression instead of anonymous delegates, which will bring a little bit readibility to our function. Sample code is below:
List<int> oddNumb2 = FilterArrayOfInts(nums, i => (i&1)==1);
ohhh what have we done :) . i=> means i goes to. Look what doe i go to ; i goes to (i&1)==1 expression result right ? and, a==b returns either true or false, so it means i goes to a boolean variable. Himm our filterarrayofints function requires a function that returns a bool right ? so that is it :)
You want more lambda expressions ? wait :)