Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a tree using LINQ

Tags:

c#

.net

linq

I have a tree created from this class.

class Node {     public string Key { get; }     public List<Node> Children { get; } } 

I want to search in all children and all their children to get the ones matching a condition:

node.Key == SomeSpecialKey 

How can I implement it?

like image 411
Ufuk Hacıoğulları Avatar asked Aug 15 '11 08:08

Ufuk Hacıoğulları


1 Answers

It's a misconception that this requires recursion. It will require a stack or a queue and the easiest way is to implement it using recursion. For sake of completeness I'll provide a non-recursive answer.

static IEnumerable<Node> Descendants(this Node root) {     var nodes = new Stack<Node>(new[] {root});     while (nodes.Any())     {         Node node = nodes.Pop();         yield return node;         foreach (var n in node.Children) nodes.Push(n);     } } 

Use this expression for example to use it:

root.Descendants().Where(node => node.Key == SomeSpecialKey) 
like image 124
vidstige Avatar answered Sep 23 '22 14:09

vidstige