首页 > 解决方案 > 如何在设置值时递归地迭代所有子属性

问题描述

我有一个树视图类。

public class TreeNode
{
     public int Id {get;set;}
     public HashSet<TreeNode> ChildNodes {get;set;}
     public TreeNode ParentNode {get;set;}
     public bool IsExpanded {get;set;}
}

默认情况下,所有树项都具有 IsExpanded = false。

当我得到叶节点时,我需要展开节点及其所有父节点,一直到根节点。

这是我到目前为止所尝试的:

//
// This method will return all Ids for the node and all its parent nodes.
//
private IEnumerable<int> YieldIdsRecursively(TreeNode node)
{
     yield return node.Id;
     if (node.ParentNode is not null)
     {
          foreach (int id in YieldIdsRecursively(node.ParentNode))
          {
               yield return id;
          }
     }
}

//
// I wanted to use the ref modifier to set the Id property of each node.
// However, properties are not supported by the ref modifier in c#
//
private void ExpandNodesRecursively(IEnumerable<int> ids, ref HashSet<TreeNode> nodes)
{
     foreach(var node in nodes)
     {
          if(ids.Contains(node))
          {
               node.IsExpanded = true;
          }

          if((node.ChildNodes?.Count ?? 0) > 0)
          {
               //
               // This is where the error pops
               //
               ExpandNodesRecursively(ids, node.ChildNodes);
          }
     }
} 

任何建议将不胜感激!

标签: c#linq

解决方案


好吧,我认为返回TreeNode本身而不是返回它更容易Id

private IEnumerable<TreeNode> ThisAndAllParents() {
  for (TreeNode current = this; current != null; current = current.ParentNode)
    yield return current;
}

那么ExpandNodesRecursively可以是这样的:

private void ExpandNodesRecursively() {
  foreach (TreeNode node in ThisAndAllParents())
    node.IsExpanded = true; 
}

推荐阅读