c# - Depth of a relationship -



c# - Depth of a relationship -

i'm trying figure out how depth of relationship of entity can relate itself. there base of operations comment item, can have 1 or more reply comments linked it.

now each 1 of these replied comments want know how deep top node.

ie, want know depth in comments in image below:

this code of now, , variable responseto relationship comment response to, if is not response value null

var comments = db.comments .where(c => c.post.id == id && c.status == helpers.statuscode.visible) .select(x => new commenttemp() { id = x.id, text = x.text, avatar = "-1", username = (x.user != null ? x.user.username : "anonymous"), userid = (x.user != null ? (int?) x.user.id : null), responseto = (x.responseto == null ? null : (int?) x.responseto.id), commentdepth = ??? // <--- how select depth of response relations? created = x.created }) .tolist();

only alternative can think of right saving comment created, if possible on fly.

well, indeed sounds want hold such info in database, unless there's really reason not to. either way, linq not recursive friendly.

you can depth creating dictionary & tracking recursively.

int getdepth(comment comment, idictionary<int, comment> comments, /*key=commentid, val=comment*/ idictionary<int, int> depthmemoization, /* key=commentid, val=depth*/ int currentdepth = 0) { if(depthmemoization.containskey(comment.id)) homecoming depthmemoization[comment.id]; if(comment.parentid==null) homecoming currentdepth; var parentcomment = comments[comment.parentid.value]; int calculateddepth = getdepth(parentcomment, comments, depthmemoization, ++currentdepth); depthmemoization[comment.id] = calculateddepth ; homecoming depth; }

c# lambda .net-4.5

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -