c# - Is there an easy way to count the elements in a recursive data structure? -


i have recursive data structure in c# object.

an object has collection of "parts." each part has collection of parts. , on. structure theoretically nest forever.

object --> part --> part   --> part   --> part     --> part   --> part --> part 

i want count of parts in structure. so, branches , leaves. (there 7 total parts, in above example.)

is there way without initializing counter , recursing down through tree? this, certainly, seems slow , overkill-ish. there better/easier way?

a natural way of processing recursive data structures, count or other kind of aggregation, employing recursive function:

class part {     ienumerable<part> subparts {get;set;}     public int totalparts {         {             return 1 + subparts.sum(p => p.totalparts);             //     ^                       ^             //     |                       |             // add 1 part       |             //                             |             //         use linq aggregate counts recursively         }     } } 

the function assumes parts of lower levels not shared among parts @ higher level, i.e. graph of parts tree. 1 way improve performance of functions cache results @ levels below yours in part, make sure recursive computation done once.

you avoid recursion implementing queue or stack, implementation wouldn't simple.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -