this related this question. (i don't have necessary reputation post comments discussion)
assuming have same model class
public class category { public int categoryid { get; set; } public string categoryname { get; set; } public int? parentcategoryid { get; set; } public string categorydesc { get; set; } [foreignkey("parentcategoryid")] public virtual category parentcategory { get; set; } [inverseproperty("parentcategory")] public virtual icollection<category> subcategories{ get; set; } public virtual icollection<product> products { get; set; } }
and use query
var topcategories = dbstore.categories.tolist().where(category => category.parentcategoryid == null);
what considered best practice organizing , using collection topcategories
?
i have similar situation in case subcategories
7 or 8 levels deep, , need know each category
within hierarchy in order build view data.
i'm using jquery treetable, , requires in hierarchical order, , there id
references parent each <tr>
in order collapsible tree work.
i believe can make work creating separate variables each level of hierarchy (by running queries on topcategories
, making individual collections each level) in the method builds viewmodel , returns view, i'm curious know if there's cleaner / more elegant way this.
thanks
i found solution i'm trying in this post.
i'm didn't ask original question in clear enough way, wanted add in case else ended down rabbit hole in on subject.
i still have reading on because don't understand of it, looking topological sort, referenced in linked post above.
here code referenced post, edited post.
if willing walk through that's happening here, appreciate it.
class flattentree { // map each item children ilookup<category, category> mapping; public flattentree(ienumerable<category> list) { var itemlookup = list.todictionary(item => item.id); mapping = list.where(i => i.parentcategoryid.hasvalue) .tolookup(i => itemlookup[i.parentcategoryid.value]); } ienumerable<item> yielditemandchildren(item node) { yield return node; foreach (var child in mapping[node].orderby(i => i.categoryname)) foreach (var grandchild in yielditemandchildren(child)) yield return grandchild; } public ienumerable<category> sort() { return grouping in mapping let item = grouping.key item.parentcategoryid == null orderby item.categoryname child in yielditemandchildren(item) select child; } }
Comments
Post a Comment