i have list of data structures:
public list<personal> personals() { return new list<personal> { new personal { id = 0, name = "name 0" }, new personal { id = 1, name = "name 1", parentid = 0 }, new personal { id = 2, name = "name 2", parentid = 0 }, new personal { id = 3, name = "name 3", parentid = 0 }, new personal { id = 4, name = "name 4", parentid = 1 }, new personal { id = 5, name = "name 5", parentid = 1 }, new personal { id = 6, name = "name 6", parentid = 2 }, new personal { id = 7, name = "name 7", parentid = 2 }, new personal { id = 8, name = "name 8", parentid = 4 }, new personal { id = 9, name = "name 9", parentid = 4 }, }; }
and want build tree:
public list<tree> trees() { return new list<tree> { new tree { id = 0, name = "name 0", list = new list<tree> { new tree { id = 1, name = "name 1", list = new list<tree> { new tree { id = 4, name = "name 4" }, new tree { id = 5, name = "name 5" } } } } } }; }
how build tree linq object? have use doesn't work exactly, see below:
public list<tree> gettree(list<personal> list) { var listformat = list.select(x => new tree { id = x.id, name = x.name, parentid = x.parentid }).tolist(); var lookup = listformat.tolookup(f => f.parentid); foreach (var tree in listformat) { tree.list = lookup[tree.id].tolist(); } return listformat; }
you should use recursion:
public void somemethod() { // here `list` var tree = gettree(list, 0); } public list<tree> gettree(list<personal> list, int parent) { return list.where(x => x.parentid == parent).select(x => new tree { id = x.id, name = x.name, list = gettree(list, x.id) }).tolist(); }
Comments
Post a Comment