tags:

views:

485

answers:

6

I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions?

They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer?

Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.

+2  A: 

Have you looked at Eric White's C# functional programming tutorial? Have a look here

Mike Thompson
A: 

code magazine has a good article this month about this, but there website is not working for me right now...
www.code-magazine.com

The crux was to really understand delegates first.

jms
+3  A: 

Lambdas bring functional programing to C#. They are anonymous functions that can be passed as values to certain other functions. Used most in LINQ.

Here is a contrived example:

List<int> myInts = GetAll();
IEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0);

Now when you foreach through evenNumbers the lamda

x=> x % 2 == 0

is then applied as a filter to myInts.

They become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops.

Brian Leahy
A: 

These are good answers, but it has also been asked before. The other question is a good resource.

Dale Ragan
+2  A: 

Here's a simple example of something cool you can do with lambdas:

List<int> myList = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
myList.RemoveAll(x => x > 5);
//myList now == {1,2,3,4,5}

The RemoveAll method takes a predicate(a delegate that takes argurments and returns a bool), any that match it get removed. Using a lambda expression makes it simpler than actually declaring the predicate.

Corey
+3  A: 

: are lambda expressions useful for anything other than querying

Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'.

So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.)

An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function.

This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you.

Will Dean