Cool Linq Trick

by Charles Cherry

I was trying to figure out how to bind to a windows forms treeview control using Linq to SQL. I stumbled across this article (http://www.simple-talk.com/dotnet/.net-framework/using-three-flavors-of-linq-to-populate-a-treeview/) on the SimpleTalk blog (one of my favorites).

Here is a very quick way to populate a two-level treeview with a single linq statement:

Dim q = From d In myDocs _
    Group By Key = d.CaseNumber Into Group _
    Select New TreeNode(Key, 0, 1, _
      (From doc In Group _
       Select New _
       TreeNode(doc.DocumentName, 2, 2)).ToArray)
TVCases.Nodes.Clear()
TVCases.Nodes.Add(New TreeNode("Select a Case", q.ToArray))

Hat tip to Michael Sorens for this code.

Advertisements