But what you don't know is that that kind of thinking truly hurts their feelings and is just wrong of you since they are in fact awesome. I'm not sure how you live with yourself.
What kind of monster are you???
But anyway, yeah. Lambda Expressions are a nice an easy way to write an inline function.
Their format is:
arguments, arrow thingy, method.
There's a few different ways to write them.
Here are some examples.
(x, y) => { return x * y; }
() => MessageBox.Show("Tina, come get some ham!");
x => x * x;
No seriously, come get some ham.
So, let's start with the arguments.
* You can have any number of arguments -- even no arguments if you're that kind of guy.
* If there are no arguments, use open and close parentheses. ()
* If there are multiple arguments, separate them by commas and surround them with parentheses. (x, y, z)
* If there's one argument, you can you parentheses if you so desire, but you don't have to.
The arrow thingy:
* Looks like this: =>
* That's about it for the arrow thingy.
The method:
* If there are multiple statements, surround with brackets. { asdf(); zxcv(); }
* If there's just one statement, brackets are optional. DoStuff()
* If it's one statement without brackets and that statement returns a value, that will be the resulting value of the expression. x => x * x
* If the method is in brackets, and you want the expression to return a value, you'll need to use the return statement. x => { return x * x;}
So, let's have some fun.
Action doSomething = () => { MessageBox.Show("asdf"); };
doSomething();
Func getSquare = x => x * x;
int y = getSquare(5);
Your mind has just been blown.
You can assign a Lambda Expression to a delegate that matches their signature.
You might not have seen Action
Action<string, string> writeFile = (fileName, fileContents) => File.WriteAllText(fileName, fileContents);
So...how is this useful?
Well, it's used a lot in LINQ which we'll get to later, but it has some other nice uses.
Ever want to log how long a method takes to run?
public static T LogTime<T>(Func<T> function, string description)
{
const string logFileName = "Timing.txt";
DateTime startTime = DateTime.Now;
T result = function();
DateTime endTime = DateTime.Now;
TimeSpan elapsedTime = endTime - startTime;
File.AppendAllText(logFileName, description + ": " + elapsedTime.TotalMilliseconds.ToString() + " ms");
return result;
}
How about doing a quick sort?
Here's a typical scenario.
You've got a whole bunch of muppets, but you really need to get them in order of how long their names are.
List<string> muppets = new List<string>{ "Ernie", "Kermit", "That weird shrimp guy", "Lew Zealand" };
muppets.Sort((muppetA, muppetB) => muppetA.Length - muppetB.Length);