c# - 如何在设置值时递归地迭代所有子属性
问题描述
我有一个树视图类。
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);
}
}
}
任何建议将不胜感激!
解决方案
好吧,我认为返回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;
}
推荐阅读
- php - PHP - 小数点增值税计算问题
- django - DoesNotExist at /cart/ 产品匹配查询不存在
- javascript - javascript - 等待用户关闭的引导模式
- html - 一个 href 没有点击
- javascript - HttpOnly cookie 仅在第二次请求后设置
- javascript - 如何使我的网络应用程序中的“任务”可编辑?
- c - 在匹配器对象中加入模糊搜索
- java - 在嵌套面板中移动标签
- python - 为什么对 numpy 数组进行就地修改的性能与被修改的维度顺序有关?
- javascript - 如何按值的降序对Javascript中的对象映射进行排序?