Thinking Linq


I’ve been comfortable using LINQ for what seems like a long time. I’m noticing that I’ve been implementing some of the lesser used functions a bit more as of late, but I’m not sure exactly when they’re appropriate. Take the following method that is a prime candidate for leveraging LINQ.

Any time you see that if inside a foreach in C#, you’ll probably want to write this differently. A year ago, I probably would have written this:

More recently, my thought process makes me want to write that same code like so:

For some reason, I like the second LINQ implementation better. It just seems to read nicer and reflect the method’s intent a bit more accurately.

I don’t have a strong preference either way, so I decided to see how different they actually are in IL:

As far as I’m concerned, these are exactly the same. I’m going to go with the second implementation, the one that uses .SkipWhile().

Using My Powers for Good