public async Task <KPITreeViewModel> GetListTreeForWorkplace(int userid) { var levels = new List <KPITreeViewModel>(); List <KPITreeViewModel> hierarchy = new List <KPITreeViewModel>(); var listLevels = await _dbContext.Levels.OrderBy(x => x.LevelNumber).ToListAsync(); var user = _dbContext.Users.FirstOrDefault(x => x.ID == userid); var levelNumber = await _dbContext.Levels.FirstOrDefaultAsync(x => x.ID == user.LevelID); if (levelNumber == null) { return(new KPITreeViewModel()); } listLevels = listLevels.Where(x => x.LevelNumber >= levelNumber.LevelNumber).OrderBy(x => x.LevelNumber).ToList(); foreach (var item in listLevels) { var levelItem = new KPITreeViewModel(); levelItem.key = item.ID; levelItem.title = item.Name; levelItem.code = item.Code; levelItem.state = item.State; levelItem.levelnumber = item.LevelNumber; levelItem.parentid = item.ParentID; levels.Add(levelItem); } var itemLevel = await _dbContext.Levels.FirstOrDefaultAsync(x => x.ID == user.LevelID); hierarchy = levels.Where(c => c.parentid == itemLevel.ParentID) .Select(c => new KPITreeViewModel() { key = c.key, title = c.title, code = c.code, levelnumber = c.levelnumber, parentid = c.parentid, children = GetChildren(levels, c.key) }) .ToList(); HieararchyWalk(hierarchy); var obj = new KPITreeViewModel(); foreach (var item in hierarchy) { if (item.key == itemLevel.ID) { obj = item; break; } } var model = hierarchy.Where(x => x.key == itemLevel.ID).FirstOrDefault(); return(model); }
/// <summary> /// Convert the nested hierarchical object to flatten object /// </summary> /// <param name="parent"></param> /// <returns></returns> public IEnumerable <KPITreeViewModel> ConvertHierarchicalToFlattenObject(KPITreeViewModel parent) { yield return(parent); foreach (KPITreeViewModel child in parent.children) // check null if you must { foreach (KPITreeViewModel relative in ConvertHierarchicalToFlattenObject(child)) { yield return(relative); } } }
public async Task <List <KPITreeViewModel> > GetListTree() { var listLevels = await _dbContext.Levels.OrderBy(x => x.LevelNumber).ToListAsync(); var levels = new List <KPITreeViewModel>(); foreach (var item in listLevels) { var levelItem = new KPITreeViewModel(); levelItem.key = item.ID; levelItem.title = item.Name; levelItem.code = item.Code; levelItem.state = item.State; levelItem.levelnumber = item.LevelNumber; levelItem.parentid = item.ParentID; levels.Add(levelItem); } List <KPITreeViewModel> hierarchy = new List <KPITreeViewModel>(); hierarchy = levels.Where(c => c.parentid == 0) .Select(c => new KPITreeViewModel() { key = c.key, title = c.title, code = c.code, levelnumber = c.levelnumber, parentid = c.parentid, children = GetChildren(levels, c.key) }) .ToList(); HieararchyWalk(hierarchy); return(hierarchy); }