❔ How to get all children of parent node?

I have a DTO as image. I want to get all children (included children of child) . How can I achive this ? Thanks
6 Replies
ero
ero2y ago
what children? i don't see any there
Thinker
Thinker2y ago
I think you'll need something like dbContext.Nodes.Where(node => node.ParentId == id) and then also do that for all of those children something like this
IEnumerable<Node> GetDescendants(Node node)
{
var children = dbContext.Nodes.Where(n => n.ParentId == node.Id);
return children.Concat(children.SelectMany(GetDescendants));
}
IEnumerable<Node> GetDescendants(Node node)
{
var children = dbContext.Nodes.Where(n => n.ParentId == node.Id);
return children.Concat(children.SelectMany(GetDescendants));
}
of course assuming you're using Entity Framework (or this isn't a database at all)
.perceptron
.perceptronOP2y ago
{ "data": [ { "id": 2, "name": "General", "parentId": "0" }, { "id": 3, "name": "Fruits", "parentId": "2" }, { "id": 6, "name": "Vegetables", "parentId": "2" }, { "id": 12, "name": "Apple", "parentId": "3" } ], "success": true, "messages": null }
ero
ero2y ago
i see yeah you wanna do what thinkger suggested
SWEETPONY
SWEETPONY2y ago
internal static class GenericHelpers
{
public static IEnumerable<TreeItem<T>> GenerateTree<T, K>(
this IEnumerable<T> collection,
Func<T, K> idSelector,
Func<T, K> parentIdSelector,
K rootId = default( K ) )
{
foreach ( var c in collection.Where( c => EqualityComparer<K>.Default.Equals( parentIdSelector( c ), rootId ) ) )
{
yield return new TreeItem<T>
{
Item = c,
Children = collection.GenerateTree( idSelector, parentIdSelector, idSelector( c ) )
};
}
}
}

var root = yourCollection.GenerateTree(
item=> item.Id,
item=> item.ParentId );
internal static class GenericHelpers
{
public static IEnumerable<TreeItem<T>> GenerateTree<T, K>(
this IEnumerable<T> collection,
Func<T, K> idSelector,
Func<T, K> parentIdSelector,
K rootId = default( K ) )
{
foreach ( var c in collection.Where( c => EqualityComparer<K>.Default.Equals( parentIdSelector( c ), rootId ) ) )
{
yield return new TreeItem<T>
{
Item = c,
Children = collection.GenerateTree( idSelector, parentIdSelector, idSelector( c ) )
};
}
}
}

var root = yourCollection.GenerateTree(
item=> item.Id,
item=> item.ParentId );
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server