Please refer below code.
Code
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtParentMenu = new DataTable();
dtParentMenu.Columns.Add("ParentMenuId", typeof(int));
dtParentMenu.Columns.Add("MenuName", typeof(string));
dtParentMenu.Rows.Add(1, "Admin");
dtParentMenu.Rows.Add(2, "Inventory");
dtParentMenu.Rows.Add(3, "Report");
DataTable dtSubMenu = new DataTable();
dtSubMenu.Columns.Add("SubmenuId", typeof(int));
dtSubMenu.Columns.Add("MenuName", typeof(string));
dtSubMenu.Columns.Add("ParentMenuId", typeof(int));
dtSubMenu.Rows.Add(1, "Dashboard", 1);
dtSubMenu.Rows.Add(2, "Add user", 1);
dtSubMenu.Rows.Add(3, "Report", 3);
List<ParentMenu> result = (from pm in dtParentMenu.AsEnumerable()
join sm in dtSubMenu.AsEnumerable()
on pm.Field<int>("ParentMenuId") equals sm.Field<int>("ParentMenuId")
select new ParentMenu
{
ParentMenuId = pm.Field<int>("ParentMenuId"),
ParentMenuName = pm.Field<string>("MenuName")
}).ToList();
List<ParentMenu> parents = new List<ParentMenu>();
foreach (var item in result)
{
List<SubMenu> ChildMenus = new List<SubMenu>();
ChildMenus.AddRange(from sm in dtSubMenu.AsEnumerable()
where sm.Field<int>("ParentMenuId").Equals(item.ParentMenuId)
select new SubMenu
{
SubMenuName = sm.Field<string>("MenuName")
});
parents.Add(new ParentMenu
{
ParentMenuName = item.ParentMenuName,
ChildMenus = ChildMenus
});
}
}
public class ParentMenu
{
public List<SubMenu> ChildMenus { get; set; }
public int ParentMenuId { get; set; }
public string ParentMenuName { get; set; }
}
public class SubMenu
{
public int SubmenuId { get; set; }
public string SubMenuName { get; set; }
public int ParentmenuId { get; set; }
}