LINQ: ‘Week Commencing’ TreeNodes

I needed a way to create a TreeView in VB.NET that contained a node for each month of the year, and each month node had to contain a node for each Monday within that month. A ‘Week Commencing’ type of view. This type of problem always seems better solved with LINQ, so here’s how I did it:

Private Function GenNode() As TreeNode

        Dim rootNode As New TreeNode("Week Commencing")

' Create a list containing every date of the year
        Dim dateList As New List(Of Date)
        Dim dateIterator As New Date(Year(Now), 1, 1)
        Do Until dateIterator.Year <> Year(Now)
            dateList.Add(dateIterator)
            dateIterator = dateIterator.AddDays(1)
        Loop

' Now, using LINQ, create the TreeNodes
        Dim t = From d In dateList Group d By m = d.Month Into Group Select
            New TreeNode(MonthName(m),
                (From d1 In dateList Where d1.Month = m And d1.DayOfWeek = DayOfWeek.Monday Select New TreeNode(d1.ToString("dd-MM-yyyy"))).ToArray) Distinct

        rootNode.Nodes.AddRange(t.ToArray)

        Return rootNode

    End Function

For more information on LINQ, see the following link 🙂

http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx