Super Lambda Bananas
I’m a big generic collection user and I can’t express how much the C# 3 Linq expressions have improved my coding experience, especially in the form of lambda syntax. I used to spend a lot of time trying to bend predicates to my will in order to pull the good stuff out of my collections, and some of the new expressions make this a thing of the past.
Some of the expressions do need a bit of extra thought to understand what is going on though. For example, what is the difference between .Where, .TakeWhile and .SkipWhile? They all return a subset of your collection, but what exactly do you get? Let’s investigate!
So say we start with this:
string[] names = {"dave", "dee", "dozy", "beaky", "mick", "titch", "darius"}; names.Where(name => name.StartsWith("d"));
.Where will return “dave”, “dee”, “dozy” and “darius”, matching everything that starts with ‘d’. TakeWhile and SkipWhile are different though, working on your sequence only until a specified condition is deemed false. So…..
names.TakeWhile(name => name.StartsWith("d"));
will return “dave”, “dee” and “dozy”: the search is called off when StartsWith(”d”) becomes false. Conversely
names.SkipWhile(name => name.StartsWith("d"));
will get you “beaky”, “mick”, “titch” and “darius”, skipping the items in the sequence until StartsWith(”d”) becomes false.
Try doing that with predicates!
