I'm a pretty big fan of Linq. I use it all the time in my C# code. But it's a relatively big library, and I've never studied it exhaustively, so from time to time I come across some neat corner of it I've never seen before. In fact, that happened just the other day.
I find that I'll frequently write test code that looks like this:
Assert.AreEqual(0, collection.Count());
or the inverse:
Assert.AreNotEqual(0, collection.Count());
I've done it often enough that I have thought I ought to write a pair of extension methods on Assert called IsEmpty and IsNotEmpty. That's probably still a good idea, but it also turns out that the Linq extension method Any (normally used to test if at least one element of an enumeration meets some criteria) also has a zero-overload method that simply returns true if the enumeration has any elements at all. So I could rewrite the above tests as:
Assert.IsFalse(collection.Any());
and
Assert.IsTrue(collection.Any());
respectively. While having Assert.IsEmpty and Assert.IsNotEmpty extension methods would be better (perhaps your test framework already provides them), this is still a handy little thing to know about.
Posted
Apr 02 2010, 03:23 PM
by
craig-andera