What is appliance and how to use lambda expressions? [duplicate]
Question
This question already has an answer here:
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.
Solution
: 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.
OTHER TIPS
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.
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.