I have written code for getting hierarchical data for the location. I am able to get the hierarchy to TWO level only, but what I'm looking for nth level hierarchy. I have written the recursive function as well, but unable to add the data into the hierarchy.
Data Model Class: -
public class RoomDTO
{
public Guid RoomId { get; set; }
public string Name { get; set; }
public Guid? ParentRoomId { get; set; }
public List<RoomDTO> Children { get; set; } = new List<RoomDTO>();
}
Parent Function:-
private List<RoomDTO> RoomData(List<SubLocation> subLocations)
{
List<RoomDTO> rooms = new List<RoomDTO>();
foreach (var location in subLocations.Where(x => x.HasChildLocations))
{
var subLocationDTO = new RoomDTO
{
RoomId = location.SubLocationId
,Children = getChild(subLocations, location, new RoomDTO()).Children
};
rooms.Add(subLocationDTO);
}
return rooms;
}
Recursive Function: -
private RoomDTO getChild(List<SubLocation> list, SubLocation location, RoomDTO roomDTO)
{
var child = list.Where(x => x.ParentSubLocationId == location.SubLocationId).ToList();
for (int i = 0; i < child.Count; i++)
{
var childRoom = new RoomDTO {
ParentRoomId = child[i].ParentSubLocationId
, RoomId = child[i].SubLocationId
};
roomDTO.Children.Add(childRoom);
getChild(list, child[i], roomDTO);
}
return locList;
}
Calling function: -
public void GetRoomList()
{
var subLocationList = _context.SubLocations.AsNoTracking().ToList();
var data = RoomData(subLocationList);
}
Please advise what incorrect I'm doing here.