title: Trying to replace a tail recursive call by a loop
body: <p>On <a href="https://stackoverflow.com/questions/9138894/findparentt-is-null-while-using-wpftoolkitdatagrid">this</a> question there is a recursive function that finds a parent :</p>
  
  <pre><code>public static T FindParent&lt;T&gt;(DependencyObject child) where T : DependencyObject
  {
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);
      if (parentObject == null) return null;
      var parent = parentObject as T;
      if (parent != null)
      {
          return parent;
      }
      return FindParent&lt;T&gt;(parentObject);
  }
  </code></pre>
  
  <p>Resharper offers me to convert it to a loop instead of recursion, it does it like that :</p>
  
  <pre><code>public static T FindParent&lt;T&gt;(DependencyObject child) where T : DependencyObject
  {
      while (true)
      {
          DependencyObject parentObject = VisualTreeHelper.GetParent(child);
          if (parentObject == null) return null;
          var parent = parentObject as T;
          if (parent != null)
          {
              return parent;
          }
          child = parentObject;
      }
  }
  </code></pre>
  
  <hr>
  
  <p>Now I have a function that collapses expanded groups and all its sub-groups :</p>
  
  <p>Unfortunately Reshaper does not offer me to convert it like the one above :(</p>
  
  <pre><code>private void MenuItemCollapseAll_OnClick(object sender, RoutedEventArgs e)
  {
      // ... truncated for brievety
      IEnumerable&lt;CollectionViewGroup&gt; groups = grid.Items.Groups.OfType&lt;CollectionViewGroup&gt;().ToArray();
      CollapseGroups(grid, groups);
  }
  
  public void CollapseGroups(DataGridControl grid, IEnumerable&lt;CollectionViewGroup&gt; groups)
  {
      foreach (var @group in groups)
      {
          grid.CollapseGroup(group);
          var subGroups = @group.Items.OfType&lt;CollectionViewGroup&gt;().ToArray();
          if (subGroups.Any())
          {
              CollapseGroups(grid, subGroups);
          }
      }
  }
  </code></pre>
  
  <p>I just can't figure out how to convert it in the same way using a <code>while</code> statement, not entirely sure whether it's possible for this very function.</p>
  
  <p>Any ideas ?</p>