c# - Recursive yield method to traverse object graph and return visited nodes -
i'm trying write extension method supposed traverse object graph , return visited objects.
i'm not sure if approach best, please comment on that. yield frying brain... i'm sure answer obvious :/
model
public class myclass { public myclass parent {get;set;} }
method
public static ienumerable<t> selectnested<t> (this t source, func<t, t> selector) t : class { yield return source; var parent = selector(source); if (parent == null) yield break; yield return selectnestedparents(parent, selector).firstordefault(); }
usage
var list = myobject.selectnested(x => x.parent);
the problem
it's working. visits 2 objects. self , parent.
so given graph c -> b -> a
starting c
. c, b
returned not quite wanted.
the result i'm looking b, c
in last line of selectnested
return first parent:
yield return selectnestedparents(parent, selector).firstordefault();
you have return parents:
foreach (var p in selectnestedparents(parent, selector)) return p;
instead of using recursion can use iteration more efficient:
public static ienumerable<t> selectnested<t>(this t source, func<t, t> selector) t : class { var current = source; while (current != null) { yield return current; current = selector(current); } }
Comments
Post a Comment