Jan 27 2012

Lambda Expressions in C#

Lambda Expressions are very powerful when it comes to filtering sets. There are built in methods such as Where() or FindAll() available for most collections in C#. These methods use Lambda Expressions for filtering. I have listed a few examples below.

Find evens in a list of positive integers


List numbers = Enumerable.Range(1, 100).ToList();
var evens = numbers.FindAll(n => n % 2 == 0);

Find primes in a list of positive integers


List numbers = Enumerable.Range(1, 100).ToList();
for (int i = 2; i < 8; i++) {
numbers = numbers.Where( n => (n > 1) && ( (n == i) || (n % i > 0) ) ).ToList();
}

Although, it is probably not necessary to explain the expression above; prime numbers cannot be devided by 2, 3, 5, 7 and not equal to 1. Why doesn’t  it matter that 4 and 6 are in the loop too? It is because 4 is a multiple of 2 and 6 is a multiple of 3. If a number is devisible by the multiple of a prime number then it must be devisible by the base prime too. Therefore anything that is devisible by 4 or 6 cannot be a prime.

Lambda Expressions can use Generic Delegates to ensure that the input, output is matching a given type. For instance, the expression below will return a compiler error because the inferred type is a double.

Func<double,double> giveMeDouble = (x) => x / 2;
int MyInt = giveMeDouble(1);

This short introduction is not even scratching the surface of what Expressions can do. If you want more information about Expressions check out ExpressionTrees on MSDN.


© George Berdal 2006-2010 All Rights Reserved


Valid HTML 4.01 Transitional