I have created a simple webapi2 program which returns a json as given below
[
{
"MenuId": 1,
"ParentMenuId": 0
},
{
"MenuId": 2,
"ParentMenuId": 1
},
{
"MenuId": 3,
"ParentMenuId": 0
},
{
"MenuId": 4,
"ParentMenuId": 3
},
{
"MenuId": 5,
"ParentMenuId": 4
},
{
"MenuId": 6,
"ParentMenuId": 3
},
{
"MenuId": 7,
"ParentMenuId": 1
},
{
"MenuId": 8,
"ParentMenuId": 4
}
]
The problem is, I need all the child to come under a parent before traversing another parent. The MenuId 6,7 & 8 should come under 8,2 & 5 respectively. That is, I need the order of this json to be exactly like this
[
{
"MenuId": 1,
"ParentMenuId": 0
},
{
"MenuId": 2,
"ParentMenuId": 1
},
{
"MenuId": 7,
"ParentMenuId": 1
},
{
"MenuId": 3,
"ParentMenuId": 0
},
{
"MenuId": 4,
"ParentMenuId": 3
},
{
"MenuId": 5,
"ParentMenuId": 4
},
{
"MenuId": 8,
"ParentMenuId": 4
},
{
"MenuId": 6,
"ParentMenuId": 3
}
]
To achieve this, i have coded a spaghetti code in c# as below, it works and gives me the result, but i need to know is there any other better way. Any advice would be helpful. Thank you.
var rolerights = new List<RoleRightsModel>();
var rights = _rightsRepository.GetRights(RoleId);
foreach (var right in rights)
{
if (right.ParentMenuId == 0)
{
rolerights.Add(right);
var rgs1 = rights.Where(p => p.ParentMenuId == right.MenuId).ToList();
foreach (var rg1 in rgs1)
{
rolerights.Add(rg1);
var rgs2 = rights.Where(p => p.ParentMenuId == rg1.MenuId).ToList();
foreach (var rg2 in rgs2)
{
rolerights.Add(rg2);
var rgs3 = rights.Where(p => p.ParentMenuId == rg2.MenuId).ToList();
foreach (var rg3 in rgs3)
{
rolerights.Add(rg3);
}
}
}
}
}
//This code works only upto two levels of nesting, if i need three levels, i need to add another loop.