遵循最后一个答案:将平面集合转换为层次集合的递归方法?
我想使用相同的方法 CreateTree 但使用除层次结构之外的另一个对象:ItemNode:
public class ItemNode
{
public string Id { get; set; }
public Item Item { get; set; }
public ICollection<ItemNode> Children { get; set; }
}
以及Item的定义:
public class Item
{
public string ID { get; set; }
public string Name { get; set; }
public int Level { get; set; }
public string ParentId { get; set; }
}
这里是带有 ItemNode 的 CreateTree 方法:
static List<ItemNode> CreateTreeItems(IEnumerable<ItemNode> nodes)
{
Dictionary<string,ItemNode> idToNode = nodes.ToDictionary(n => n.Id, n => n);
List<ItemNode> roots = new List<ItemNode>();
ItemNode root = null;
foreach (var n in nodes)
{
if (n.Item.ParentId == null)
{
if (root != null)
{
roots.Add(root);
}
root = n;
continue;
}
ItemNode parent = idToNode[n.Item.ParentId];
//if (!idToNode.TryGetValue(n.Item.ParentId, out parent))
//{
// //Parent doesn't exist, orphaned entry
//}
parent?.Children.Add(n);
// RETURNS FALSE WHEREAS IN THE ORIGINAL METHOD IT RETURNS TRUE
var test = Object.ReferenceEquals(parent, root);
Debug.WriteLine(test);
}
if (root == null)
{
//There was no root element
}
roots.Add(root);
return roots;
}
它不起作用,因为 parent 和 root 没有引用同一个对象(而在原始方法中,它确实如此)。我想这与我在 ItemNode 类中添加了一个 Item 属性有关。但我不知道如何解决它。
谢谢 !