title: flat list to hierarchy
body: <p>I'm having the hardest time converting a list(Of Folder) into a hierarchy.</p>
  
  <pre><code>Public Class Folder
  
  Public Property FolderID() As Integer
  Public Property Name() As String
  Public Property ParentFolderID() As Integer
  Public Property Children() as IEnumerable(Of Folder)
  
  End Class
  </code></pre>
  
  <p>I need to return List(Of Folder) with Children populated.</p>
  
  <p>I build a List(Of Folder) from the data in the database.</p>
  
  <p>{1, "Folder 1", Nothing}
  {2, "Folder 2", 1}
  {3, "Folder 3", 2}
  {4, "Folder 4", 3}
  {5, "Folder 5", Nothing}</p>
  
  <p>I can't figure out how to recursively move the child folders into the Children property of their parent. </p>
  
  <p>I would like to do this with LINQ.</p>
  
  <p>Any help is greatly appreciated.</p>
  
  <p><strong>Update</strong></p>
  
  <p>Thank you for your answer, but not quite there. Based on your answer, I came up with this which almost works. </p>
  
  <pre><code>Dim list = (From folder in folderList Select New Folder() With {
      .FolderID = folder.FolderID, 
      .Name = folder.Name, 
      .ParentFolderID = folder.ParentFolderID, 
      .Children = (From child in folderList 
                   Where child.ParentFolderID = item.FolderID).ToList()}).ToList()
  
  {1, "Root", Nothing}
  {2, "Child", 1}
  {3, "Grand Child", 2}
  </code></pre>
  
  <p>I get a list of all three folders:</p>
  
  <pre><code>Root
  --Child
  Child
  --Grand Child
  Grand Child
  </code></pre>
  
  <p>Should look like:</p>
  
  <pre><code>Root
  --Child
  ----Grand Child
  </code></pre>