Collection comprehension

F# (and Ruby, I am told) has a nice little syntactic feature called “comprehension” which allows developers to create lists of numbers or characters by specifying a range to be “expanded”, like this:

let numbers = [0 .. 9]
let alpha = ['A' .. 'Z']
let everyOtherNumber = [0 .. 2 .. 16]

printfn "%A" numbers // [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]
printfn "%A" alpha // ['A'; 'B'; 'C'; ... 'X'; 'Y'; 'Z']
printfn "%A" everyOtherNumber // [0; 2; 4; 6; 8; 10; 12; 14; 16]

Today I’ve been working on an e-commerce project where I need to build a list of months, so I started looking for a comprehension equivalent in C# and found this less elegant but adequate (for my purposes) method on Enumerable that does something similar:

IEnumerable<Int32> months = Enumerable.Range(1, 12);

There are a few problems with Range, however:

  1. the signature is (int start, int count) instead of (int start, int end)
  2. Range only accepts and returns integers
  3. Range does not provide a means to “step” values

If anyone knows a better comprehension alternative in C#, please let me know!