The Good Stuff Is Hidden

Intellisense is great, but it is no substitute for reading documentation. I’m always upset when I hear developers say that their primary source of learning is looking at what intellisense offers them.

There are a few methods which can be considered part of LINQ, which aren’t extension methods. This means that unless you actually type out Enumerable, you will never see then in intellisense. The nature of extensions methods means that you won’t ever type out enumerable, so these methods are less discoverable than others.

System.Linq.Enumerable is where the library implementation of LINQ to objects lives. Empty, Range and Repeat methods are hand tools.

Empty is useful for those cases when you don’t want a null object, but instantiating an Enumerable is wasteful. For example, creating a new empty List of string to pass to a linq expression when some other data source may return null or empty. I’m thinking of combining linq expressions here. The anti-wasteful programmer might say “well, just use a new empty string array”. And that programmer would be right. This would use less memory than a new List. But the really nice part about Empty is that its underlying implementation is just a generic singleton based on type. That means instead of 1000 or 100,000 “new string[0]” in your code, eating up a tiny bit of ram (ok, its pretty small here, I know, but doesn’t every little bit help?) you have only one empty string array that all cases can share.

Range should be familiar to anyone coming from python. It just returns an enumerable range of numbers from start to end. IMO it isn’t as nice as pythons, but I can always write my own. Still not clear? Here is how you would write a summary from one to one hundred million of n-1 + 1/i.

var x = Enumerable.Range(1, 100000000).Aggregate(0f, (a, b) => (float)(a + 1 / (float)b));

That is: sumOfFractions_2007-12-03_10-42-46

Finally, Repeat is similar to range, it just gives an enumerator which yields the same object/value repeatedly.

Example of using repeat to make 5 hello worlds:

var fiveWorlds = Enumerable.Repeat(“Hello World”, 5);
Console.WriteLine(fiveWorlds.Aggregate((a,b)=>a + “\n” +b ));

1 thought on “The Good Stuff Is Hidden”

Comments are closed.