树结构中的左右值计算

树形结构数据存储方案(简单介绍)

方案1:继承关系驱动的Schema设计

  • 优点:直观
  • 缺点:查询效率低

方案2:基于左右值编码的Schema设计

在方案1的基础上计算左右值

        /// <summary>
        /// 计算树节点左右值
        /// </summary>
        /// <param name="trees">树节点集合</param>
        /// <param name="parentId">父节点</param>
        /// <param name="left">左值,初始为1</param>
        /// <returns></returns>
        private async Task<int> CalcLeftAndRight(IEnumerable<ProjectTreeDto> trees, string parentId, int left)
        {
            var right = left + 1;
            var result = trees.Where(q => q.ParentId.ToString() == parentId).ToList();
            for (int i = 0; i < result.Count(); i++)
            {
                right = await CalcLeftAndRight(trees, result[i].Id.ToString(), right);
            }

            StringBuilder sql = new StringBuilder();
            sql.Append($"update project_trees set LeftValue = {left}, RightValue = {right} where Id = '{parentId}'");

            await _dbContext.Database.ExecuteSqlCommandAsync(sql.ToString());

            return right + 1;
        }
posted @ 2019-11-11 18:32  传说中的路人甲  阅读(1255)  评论(0编辑  收藏  举报