tags:

views:

266

answers:

4

Can anyone give me a good explanation of how to use Lamda and give a good example. I have seen it but I dont know what it is or does.

+1  A: 

A Lambda is simply a delegate, its an anonymous function that you can create for later execution.

A Lambda Expression is an uncompiled delegate in the form of an Expression Tree that you can manipulate before compiling and executing.

http://msdn.microsoft.com/en-us/library/bb397687.aspx

Andrew Bullock
A Lamda Expression is not a delegate. It is easily convertable to a delegate, but it is also convertable to an Expression Tree, which does not hold for a delegate. See http://msdn.microsoft.com/en-us/library/bb397951.aspx
Manu
fair point, updated
Andrew Bullock
+9  A: 

A lambda expression is used to create an anonymous function. Here an anonymous function is assigned to a delegate variable:

Func<int, int> increase = (a => a + 1);

You can then use the delegate to call the function:

var answer = increase(41);

Usually lambda expressions are used to send a delegate to a method, for example sending a delegate to the ForEach method so that it's called for each element in the list:

List<int> list = new List<int>();
list.Add(1);
list.Add(2);

list.ForEach(n => Console.WriteLine(n));
Guffa
Thank you for your answer. I can see the tremendous power of it and how much time it can save
Zyon
Also it is possible from within a lambda to access the variables in the outer function scope. So in the above example you can access the list object within the lambda expression.
Oliver
+3  A: 

I did a post a while back which I hope may be of some use: http://www.dontcodetired.com/blog/?tag=/lambda+expressions

Jason Roberts
+2  A: 

Perhaps I'm being a bit simplistic, but, if I were you, to start with I'd just consider lambdas as a nice way to shorten code by removing things like nested foreach loops or top n elements.

So if you're running round hotels to find some with cheap rooms you could (assuming hotels in IEnumerable):

cheapHotels = hotels.Where(h => h.PriceFrom < 50)

Once this starts to click you can move onto something more complex, this is a random method that I can find in my current project using lambdas (probably nicked from somewhere else!):

private T DeserializeObject<T>(XmlDocument xDoc, string typeName)
{
    Type type = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Single(t => t.FullName == typeName);

    object o;
    var serializer = new XmlSerializer(typeof(T));
    using (TextReader tr = new StringReader(xDoc.InnerXml))
    {
        o = serializer.Deserialize(tr);
        tr.Close();
    }
    return (T)o;

}
amelvin