2011-11-14 29 views

答えて

6

、次はあなたの問題のためであります):

 IList<TreeNode> ancestorList = TreeHelpers.GetAncestors(node, x => x.Parent).ToList(); 

はなぜリスト<> .Add()を使用するよりも、この良いですか? --FirstOrDefault(x => ...)などのLazy LINQ関数を使用できるため、

P.S.列挙結果に「現在の」アイテムが含まれるように、代わりにTItem curItem = getParentFunc(item)

2

実際のオブジェクトが必要な場合は、ルートに達するまでTreeNode.Parentプロパティを再帰的に使用します。何かのように:あなたのコンテキストで(

public static class TreeHelpers 
    { 
     public static IEnumerable<TItem> GetAncestors<TItem>(TItem item, Func<TItem, TItem> getParentFunc) 
     { 
      if (getParentFunc == null) 
      { 
       throw new ArgumentNullException("getParentFunc"); 
      } 
      if (ReferenceEquals(item, null)) yield break; 
      for (TItem curItem = getParentFunc(item); !ReferenceEquals(curItem, null); curItem = getParentFunc(curItem)) 
      { 
       yield return curItem; 
      } 
     } 

     //TODO: Add other methods, for example for 'prefix' children recurence enumeration 
    } 

をと使用方法の例:私は、たとえば、独自のツリーヘルパーのセットを作成することをお奨めするのだ

private void GetPathToRoot(TreeNode node, List<TreeNode> path) 
{ 
    if(node == null) return; // previous node was the root. 
    else 
    { 
     path.add(node); 
     GetPathToRoot(node.Parent, path); 
    } 
} 
-1

の私は、あなたがノード

List<TreeNode> resultNodes = new List<TreeNode>() 
private void GetNodesToRoot(TreeNode node) 
{ 
    if(node == null) return; // previous node was the root. 
    else 
    { 
     resultNodes.add(node); 
     GetNodesToRoot(node.Parent); 
    } 
} 
+0

何地獄の男の配列を取る必要があると思う、TItem curItem = itemを使うのか?あなたは私のコードをコピーしました。 – Tudor

+1

ちょっと違反...私はちょうどあなたが2番目のパラメータを必要としないことを意味した –

関連する問題