c# - Search Hierarchical List Recursively -


i have hierarchical list of objects. assume structure follows:

  • root node
    • parent node
      • child node
    • parent node
      • child node
    • parent node
      • child node

the child nodes have own children, objective search "parent nodes". so, let's parent node class has property called "name" - , user enters partial name, want of parent nodes name contains user's search criteria returned. basically, more of "filter" functionality anything. so, know how this, however, problem running key objective keep hierarchical structure in tact. in other words, if there 1 parent node matches filter criteria, want structure below returned:

  • root node
    • parent node
      • child node

my current efforts yield:

  • parent node
    • child node

i using linq. suggestions appreciated.

thanks!

chris

code snippet below current filter implementation:

filteredreports = reports.firstordefault().children.cast<ihierarchicalresult>()                                     .selectrecursive(item => item.children.cast<ihierarchicalresult>())                                     .where(item => item.name.tolower().startswith(filtercriteria))                                     .toobservablecollection(); 

here extension method using:

public static ienumerable<t> selectrecursive<t>(this ienumerable<t> source, func<t, ienumerable<t>> getchildren)     {         if (null == source)         {             throw new argumentnullexception("source");         }          if (null == getchildren) return source;          return selectrecursiveiterator(source, getchildren);     }      private static ienumerable<t> selectrecursiveiterator<t>(ienumerable<t> source, func<t, ienumerable<t>> getchildren)     {         foreach (t item in source)         {             yield return item;              ienumerable<t> children = getchildren(item);             if (null != children)             {                 foreach (t child in selectrecursiveiterator(children, getchildren))                 {                     yield return child;                 }             }         }     } 

since root node want returned not same original root node (it has less children) you'll need create new root node containing children match.

something like

  node oldrootnode = ...   list<node> filteredchildren = oldrootnode.children.where(...).tolist();   node newrootnode = new node {name = oldrootnode.name, children = filteredchildren};    return newrootnode; 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -