The Mysterious Land of Lambdas and Fat Arrows

I’ve used LINQ for a while now and while I’m pretty comfortable with the syntax and how to get what I want out of it, I’m not really familiar with the magic that is happening when I type the magical fat arrow. Let’s change that!

For this totally awesome example, let’s say I need to get some octopuses (yes, octopuses. Not octopi.) A few years ago I would selected them this way:

var octopuses = from octopus in Animals
where octupus.Type == "Octopus"
select octopus;

This is cool and all but I got beat up the C# cool kids playground because lambda’s are the cool thing and linq expressions are “too wordy” and “too readable.” Also, there was less typing involved and I’m all for that! So my new way of writing this would look like:

var octopuses = Animals.Where(octopus => octopus.Type == "Octopus");

Granted, the lambda expression is much more terse and in same ways I liked it better but I really didn’t understand what was being done there. I know of the fat arrow but I don’t really KNOW the fat arrow. It’s just that thing I typed to get what I want. And that’s no way to treat our operators HMMMMMMMM???

Sadly, it didn’t take long to discover what all of this meant. Here’s goes!

For starters, in C#, the fat arrow is known as the lambda operator and it basically indicates an anonymous method. So, parameters on the left are inputs to the method on the right. Something similar to this would be:

var octopus2 = octopuses.Where(delegate(Octopus c) { return c.Name == "Sidney"; });

So really, the lambda gives a shorthand way to express a delegate that in this case was passed into the Where() method.

As you can see, this is barely readable and it would only be a matter of time before Barry (that Barry, that guy, you know EXACTLY who I’m talking about) would write one of his terrible queries on his way out the door because he’s running late to a head cheese party. He’d be gone and there would be a check-in conflict (like always…BARRY) where you’d witness something like this:

var octopus3 = octopuses.Where(delegate(Octopus y) { return y.Name == "Sidney"; })
.Where(delegate(Octopus u) { return u.Stench >= 0.2f; })
.OrderBy(delegate(Octopus c) {return c.Color;});

It’s not entirely un-readable but there’s a lot of noise that shouldn’t be there. This is the magic of the fat arrow. Having never really written a delegate like this, I didn’t realize how much heartache it was saving me.

So to summarize…

Instead of:

delegate(Octopus c){ return c.Name == "Sidney";}

You can use the short hand expression which looks like this:

c => c.Name == "Sidney"

And now I know.