Following the last answer : Recursive method to convert flat collection to hierarchal collection?
I want to use the same method CreateTree but with another object than Hierarchy: ItemNode:
public class ItemNode
{
public string Id { get; set; }
public Item Item { get; set; }
public ICollection<ItemNode> Children { get; set; }
}
and the definition of Item:
public class Item
{
public string ID { get; set; }
public string Name { get; set; }
public int Level { get; set; }
public string ParentId { get; set; }
}
And here the CreateTree methods with the ItemNode:
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;
}
It does not work because parent and root does not reference the same object (whereas in the original method, it does). I guess it was linked to the fact that I have added an Item property to the ItemNode class. But I don't know how to fix it.
Thank you !