DataReaders, LINQ to XML and Range Generation

I’m doing a bunch of database / XML stuff @ work, so I decided to use to VS08 beta 2 so I can use LINQ. For reasons I don’t want to get into, I needed a way to convert arbitrary database rows, read using a SqlDataReader, into XML. LINQ to SQL was out, since the code has to work against arbitrary tables (i.e. I have no compile time schema knowledge). But XLinq LINQ to XML helped me out a ton. Check out this example:

const string ns = "{http://some.sample.namespace.schema}";

while (dr.Read())
    XElement rowXml = new XElement(ns + tableName,
        from i in GetRange(0, dr.FieldCount)
        select new XElement(ns + dr.GetName(i), dr.GetValue(i)));

That’s pretty cool. The only strange thing in there is the GetRange method. I needed an easy way to build a range of integers from zero to the number of fields in the data reader. I wasn’t sure of any standard way, so I wrote this little two line function:

IEnumerable<int> GetRange(int min, int max)
    for (int i = min; i < max; i++)
        yield return i;

It’s simple enough, but I found it strange that I couldn’t find a standard way to generate a range with a more elegant syntax. Ruby has standard range syntax that looks like (1…10), but I couldn’t find the equivalent C#. Did I miss something, or am I really on my own to write a GetRange function?

Update: As expected, I missed something. John Lewicki pointed me to the static Enumerable.Range method that does exactly what I needed.


AFAIK there's no standard way of doing it, but you could add an extension method to 'Int32' public static IEnumerable RangeFromZero(this int number) { for (int i = 0; i < number; i++) { yield return i; } } and have something like from i in dr.FieldCount.RangeFromZero() or from i in dr.FieldCount.Range(0) with a 'Range' extension method, which is the same that you wrote but a little cooler ;).
Even better is to add an Extension method to IDataReader to make it enumerable of IDataRecord, I mean semantically it is anyway... public static IEnumerable Enumerate(this IDataReader reader) { using (reader) { while (reader.Read()) yield return reader; } } Then you can do from r in reader.Enumerate() from i in GetRange(...) etc....
I believe System.Linq.Enumerable.Range() is exactly the same as your GetRange method.
Another minor improvement: XNamespace ns = "http://some.sample.namespace.schema"; while (dr.Read()) { XElement rowXml = new XElement(ns + tableName, from i in Enumerable.Range(0, dr.FieldCount) select new XElement(ns + dr.GetName(i), dr.GetValue(i))); }