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.
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.
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));
I did a post a while back which I hope may be of some use: http://www.dontcodetired.com/blog/?tag=/lambda+expressions
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;
}