I’m finally getting into the groove with LINQ and lambda expressions, and am over the initial skepticism I had regarding the feature. My initial reaction was based on using LINQ for DB access, and was along the lines of “Pfft. There’s no way I’m embedding SQL [essentially] in my code – think of the maintenance!“
(I’ve since re-thought that somewhat, but that’s another story)
Putting databases completely aside, it took me some time to realize how much LINQ can really shine. So much of programming is about taking some data, querying it, and then doing something with it. Remember when you first started using foreach loops, and how they felt so much cleaner than for/while loops? Well, the jump to LINQ/lambda is so much greater in legibility and simplicity.
I’m not talking about hard-core stuff like a ray-tracer in one LINQ expression, I’m talking about simple every day things that would normally require a loop and some state. Some hypothetical examples (forgive my compiler-less syntax):
Find the closest point from a set of points:
Simple collision detection:
Finding the distinct set of first names from all the people you know:
Reset a property for all items in a list:
Try to recreate those using traditional loops and see how the code reads in comparison. LINQ is a thing of beauty! And consider what happens when PLINQ is in play, and your code is automatically multi-core aware.
The more I get used to doing this, the more places I realize it applies; the more I feel like I’m writing my program rather than trying to speak the compiler’s language.
Next time you see a loop – ask yourself whether it really needs to be there…