Can anyone give me a good explanation of how to use Lambda and give a good example. I have seen it but I dont know what it is or does.
-
I highly recommend not visiting that site because it looks like ad spam to me. – MetaGuru Aug 06 '13 at 13:30
4 Answers
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));

- 687,336
- 108
- 737
- 1,005
-
Thank you for your answer. I can see the tremendous power of it and how much time it can save – Zyon Feb 25 '10 at 11:57
-
1Also 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 Feb 25 '10 at 12:11
I did a post a while back which I hope may be of some use: http://www.dontcodetired.com/blog/?tag=/lambda+expressions

- 606
- 4
- 9
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.

- 36,616
- 34
- 155
- 231
-
2A 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 Feb 25 '10 at 11:37
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;
}

- 8,919
- 4
- 38
- 59