this is my first question and sorry about my weak language.
I\'ve got a table like this model;
public class Menu
{
[Key]
public int ID
I will try something like this.
This query will take all menu records from the database and will create dictionary with ParentId for key and all menus for specific parent id as values.
// if you're pulling the data from database with EF
var map = (from menu in ctx.Menus.AsNoTracking()
group by menu.ParentId into g
select g).ToDictionary(x => x.Key, x => x.ToList());
Now we can iterate the parentIds and create MyMenu instances very easly
var menusWithChildren = new List()
foreach(var parentId in map.Keys)
{
var menuWithChildren = new MyMenu { ... }
menuWithChildren.AddRange(map[parentId]);
}
Now you have list with the associations. This way you will have the children and parent associated by reference (no dublicate references across different nesting levels) But i wonder how do you define the roots, if you need to know them at all ? I don't know if this is suitable for you.