Recursive Linq

I’ve been using Common Table Expressions a lot lately. Particularly when populating SQL Databases with test data. I┬árecommend┬áchecking them out if you write slightly more than a modicum of SQL.

Just briefly – if you’re not familiar with CTE’s or their uses – imagine needing to populate a table like this: Months(Id int, MonthNo int, Year int) – with values between say Jan 2000 and Jan 2010. You might do something like this…

    WITH months(id, mnth, yr) 
     AS (SELECT 1, 
         UNION ALL 
         SELECT id + 1, 
                ( mnth % 12 ) + 1, 
                yr + ( mnth / 12 ) 
         FROM   months 
         WHERE  yr < 2010) 
FROM   months 
OPTION(maxrecursion 500)

Now onto the Recursive Linq bit (not to be confused with a Recursive Link.)

Just recently, I was building a Schedule class that required functionality similar to the above SQL. That is, I needed to split some span of time up into N DateTimes based on some function.
Continue reading