• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#使用二叉树算法设计一个无限分级的树表

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

效果图:

数据库:

操作树的示意图:

 

控制器代码:

using Dw.Business;
using Dw.Entity;
using Dw.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Diagnostics;
using System.Data;

namespace Dw.Web.Areas.School.Controllers
{
    public class SitesController : PublicController<Sites>
    {
        SitesBll sitesbll = new SitesBll();
        SitesDetailsBll sitesdetailsbll = new SitesDetailsBll();
        Sys_UserBll userbll = new Sys_UserBll();
        private Sys_DataDictionaryBll Sys_datadictionarybll = new Sys_DataDictionaryBll();
        public override ActionResult Form()
        {
            string KeyValue = Request["KeyValue"];
            //添加时获取的Id值
            string Id = Request["Id"];
            string Name = Request["Name"];

            Sites entity = new Sites();
            string SMSV,ALSV,ParentName="";
            if (string.IsNullOrEmpty(KeyValue))
            {
                SMSV = "";
                ALSV = "";
                entity = null;
            }
            else
            {
                entity = repositoryfactory.Repository().FindEntity(KeyValue);
                SMSV = entity.ShowMode;
                ALSV = entity.Accesslimit;

                var pent = repositoryfactory.Repository().FindEntity(entity.ParentId);
                ParentName = pent.Name;
            }        
            //显示模式和权限限制下拉菜单
            List<Sys_DataDictionaryDetail> ShowModeList = Sys_datadictionarybll.GetDataDictionaryDetailListByCode("ShowMode");
            List<Sys_DataDictionaryDetail> Accesslimit = Sys_datadictionarybll.GetDataDictionaryDetailListByCode("Accesslimit");
            var sml=ShowModeList.Select(m => new SelectListItem { Text = m.FullName, Value = m.Code });
            var al = Accesslimit.Select(m => new SelectListItem { Text = m.FullName, Value = m.Code });
            ViewBag.ShowMode = new SelectList(sml, "Value", "Text", SMSV);
            ViewBag.Accesslimit = new SelectList(al, "Value", "Text", ALSV);
            //获取栏目的父栏目名称和对应的值
            ViewBag.Parent = ParentName;
            //添加栏目时获取父栏目名称和Id值
            if (Id != "0"&&Id!=null)
            {
                var ent = repositoryfactory.Repository().FindEntity(Id);
                ViewBag.AddParent = Id + "," + ent.Name;
            }

            if (ManageProvider.Provider.Current().Account == "System")
            {
                List<Sys_User> userList = userbll.GetList();
                //将数据封装到 SelectList中,制定要生成下拉框选项的value和text属性  
                SelectList uList = new SelectList(userList, "UserId", "RealName");
                ViewBag.uList = uList.AsEnumerable();
            }
            else {
                var UserId = ManageProvider.Provider.Current().UserId;
                Sys_User User = new Sys_User();
                User = userbll.GetList().SingleOrDefault(a => a.UserId == UserId);
                string CompanyId = User.CompanyId;
                List<Sys_User> userList = userbll.GetList().Where(a => a.CompanyId == CompanyId).ToList();
                //将数据封装到 SelectList中,制定要生成下拉框选项的value和text属性  
                SelectList uList = new SelectList(userList, "UserId", "RealName");
                ViewBag.uList = uList.AsEnumerable();
            }

            return View(entity);
        }

        /// <summary>
        /// 提交表单
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <param name="KeyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        [LoginAuthorize]
        public override ActionResult SubmitForm(Sites entity, string KeyValue)
        {
            try
            {
                int IsOk = 0;
                string Message = KeyValue == "" ? "新增成功。" : "编辑成功。";
                if (!string.IsNullOrEmpty(KeyValue))
                {
                    Sites Oldentity = repositoryfactory.Repository().FindEntity(KeyValue);//获取没更新之前实体对象
                    if (entity.AuditUserId != null)
                    {
                        Sys_User User = new Sys_User();
                        User = userbll.GetEntity(ManageProvider.Provider.Current().UserId);
                        string AuditUserName = User.RealName;
                        entity.AuditUserName = AuditUserName;
                    }
                    else {

                    }

                    entity.CompanyId= ManageProvider.Provider.Current().CompanyId;
                    entity.Modify(KeyValue);
                    IsOk = repositoryfactory.Repository().Update(entity);
                    if (entity.ParentId != Oldentity.ParentId)
                    {
                        sitesbll.UpLR(0);
                    }
                    WriteLog(IsOk, entity, Oldentity, KeyValue, Message);
                }
                else
                {
                    if (ManageProvider.Provider.Current().Account == "System")
                    {

                    }
                    else {

                        if (entity.AuditUserId != null)
                        {
                            Sys_User User = new Sys_User();
                            User = userbll.GetList().SingleOrDefault(a => a.UserId == entity.AuditUserId);
                            string AuditUserName = User.RealName;
                            entity.AuditUserName = AuditUserName;
                        }
                        else {

                        }

                        entity.CompanyId = ManageProvider.Provider.Current().CompanyId;

                    }
                    entity.Create();
                    string strId = SysFactory.BaseHelper().GetSortCode<Sites>("Id").ToString();
                    entity.Id = int.Parse(strId);
                    IsOk = repositoryfactory.Repository().Insert(entity);
                    sitesbll.UpLR(0);
                    WriteLog(IsOk, entity, null, KeyValue, Message);
                }
                return Json(new { Success = true, Code = IsOk.ToString(), Message = Message });
            }
            catch (Exception ex)
            {
                WriteLog(-1, entity, null, KeyValue, "操作失败:" + ex.Message);
                return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
            }
        }

        /// <summary>
        /// 删除栏目数据
        /// </summary>
        /// <param name="KeyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ManagerPermission(PermissionMode.Enforce)]
        public ActionResult DeleteClass(string KeyValue)
        {
            try
            {
                string Message = "删除失败。";
                int IsOk = 0;
                var sitesdetailsitem = sitesdetailsbll.FindList().Where(a => a.SitesId== int.Parse(KeyValue)).ToList();
                var sitesitem = sitesbll.FindList().Where(a => a.ParentId == int.Parse(KeyValue)).ToList();
                if (sitesdetailsitem.Count == 0)
                {
                    if (sitesitem.Count == 0)
                    {
                        sitesbll.DelRelated(int.Parse(KeyValue));
                        IsOk = repositoryfactory.Repository().Delete(KeyValue);
                    }

                    else {
                        Message = "该栏目下含有子栏目,不能删除";
                    };
                }
                else {
                    Message = "该栏目下含有文章,不能删除";
                };
     
          
                ////批量父子栏目删除
                //sitesbll.DelRelated(int.Parse(KeyValue));
                //IsOk = repositoryfactory.Repository().Delete(KeyValue);
                if (IsOk > 0)
                {
                    Message = "删除成功。";
                }
                WriteLog(IsOk, KeyValue, Message);
                return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());
            }
            catch (Exception ex)
            {
                WriteLog(-1, KeyValue, "操作失败:" + ex.Message);
                return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
            }
        }

        /// <summary>
        /// 栏目分类列表(返回树JSON)
        /// </summary>
        /// <returns></returns>
        public ActionResult TreeJson()
        {
            string CompanyId = ManageProvider.Provider.Current().CompanyId;
            var list = repositoryfactory.Repository().FindList("ORDER BY SortCode ASC").Where(a=>a.CompanyId==CompanyId).ToList();
            List<TreeJsonEntity> TreeList = new List<TreeJsonEntity>();
        
            foreach (Sites item in list)
            {
                int DataDictionaryId = item.Id;
                bool hasChildren = false;
                List<Sites> childnode = list.FindAll(t => t.ParentId == DataDictionaryId);
                if (childnode.Count > 0)
                {
                    hasChildren = true;
                }
                TreeJsonEntity tree = new TreeJsonEntity();
                tree.id = DataDictionaryId.ToString();
                tree.text = item.Name;
                tree.value = item.ParentId.ToString();
                tree.Attribute = "IsTree";
                //tree.AttributeValue = item.IsTree.ToString();
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.ParentId.ToString();
                TreeList.Add(tree);
            }
            return Content(TreeList.TreeToJson());
        }
        public ActionResult TreeGridListJson()
        {
            string CompanyId = ManageProvider.Provider.Current().CompanyId;
            var ListData = sitesbll.GetTable(CompanyId);
            var aa = ListData.ToString();
            StringBuilder sb = new StringBuilder();
            sb.Append("{ \"rows\": ");
            sb.Append(ListData.ToJson());
            sb.Append("}");
            return Content(sb.ToString());
        }

        /// <summary>
        /// 上移栏目数据
        /// </summary>
        /// <param name="KeyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ManagerPermission(PermissionMode.Enforce)]
        public ActionResult Up(string KeyValue)
        {
            try
            {
                string Message = "上移失败。";
                int IsOk = 0;
                string CompanyId = ManageProvider.Provider.Current().CompanyId;
                var site1= sitesbll.GetEntity(int.Parse(KeyValue));
                var level = site1.Level;
                var site2 = sitesbll.FindList().SingleOrDefault(a => a.Level == site1.Level && a.CompanyId==CompanyId && a.Rgt==site1.Lft-1);
                if(site2!=null)
                {
                    int? count1 = site1.Rgt - site1.Lft + 1;
                    int? count2 = site2.Rgt - site2.Lft + 1;
                    var sitesitem1 = sitesbll.FindList().Where(a => a.Lft>=site1.Lft && a.Rgt<=site1.Rgt).ToList();
                    var sitesitem2 = sitesbll.FindList().Where(a => a.Lft >= site2.Lft && a.Rgt <= site2.Rgt).ToList();
                    foreach (var item in sitesitem1)
                    {
                        item.Lft = item.Lft - count2;
                        item.Rgt = item.Rgt - count2;
                        item.Code = item.Code - count2/2;
                        IsOk = repositoryfactory.Repository().Update(item);
                    }

                    foreach (var item in sitesitem2)
                    {
                        item.Lft = item.Lft + count1;
                        item.Rgt = item.Rgt + count1;
                        item.Code = item.Code + count1 / 2;
                        IsOk = repositoryfactory.Repository().Update(item);
                    }
                }
                else {
                    Message = "该栏目已经是该等级的最上层栏目不能上移!";
                };

                if (IsOk > 0)
                {
                    Message = "上移成功。";
                }
                WriteLog(IsOk, KeyValue, Message);
                return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());
            }
            catch (Exception ex)
            {
                WriteLog(-1, KeyValue, "操作失败:" + ex.Message);
                return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
            }
        }

        /// <summary>
        /// 下移栏目数据
        /// </summary>
        /// <param name="KeyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ManagerPermission(PermissionMode.Enforce)]
        public ActionResult Down(string KeyValue)
        {
            try
            {
                string Message = "下移失败。";
                int IsOk = 0;
                string CompanyId = ManageProvider.Provider.Current().CompanyId;
                var site1 = sitesbll.GetEntity(int.Parse(KeyValue));
                var level = site1.Level;
                var site2 = sitesbll.FindList().SingleOrDefault(a => a.Level == site1.Level && a.CompanyId == CompanyId && a.Lft== site1.Rgt + 1);
                if (site2 != null)
                {
                    int? count1 = site1.Rgt - site1.Lft + 1;
                    int? count2 = site2.Rgt - site2.Lft + 1;
                    var sitesitem1 = sitesbll.FindList().Where(a => a.Lft >= site1.Lft && a.Rgt <= site1.Rgt).ToList();
                    var sitesitem2 = sitesbll.FindList().Where(a => a.Lft >= site2.Lft && a.Rgt <= site2.Rgt).ToList();
                    foreach (var item in sitesitem1)
                    {
                        item.Lft = item.Lft + count2;
                        item.Rgt = item.Rgt + count2;
                        item.Code = item.Code + count2 / 2;
                        IsOk = repositoryfactory.Repository().Update(item);
                    }
                    foreach (var item in sitesitem2)
                    {
                        item.Lft = item.Lft - count1;
                        item.Rgt = item.Rgt - count1;
                        item.Code = item.Code - count1 / 2;
                        IsOk = repositoryfactory.Repository().Update(item);
                    }
                }
                else {
                    Message = "该栏目已经是该等级的最下层栏目不能下移!";
                };

                if (IsOk > 0)
                {
                    Message = "下移成功。";
                }
                WriteLog(IsOk, KeyValue, Message);
                return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());
            }
            catch (Exception ex)
            {
                WriteLog(-1, KeyValue, "操作失败:" + ex.Message);
                return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
            }
        }

    }
}

逻辑层代码:

using Dw.Entity;
using Dw.Repository;
using Dw.Utilities;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Dw.DataAccess;
using System.Data.Common;

namespace Dw.Business
{
    /// <summary>
    /// 网站栏目管理
    /// </summary>
    public class SitesBll : RepositoryFactory<Sites>
    {
        public List<Sites> GetList()
        {
            StringBuilder WhereSql = new StringBuilder();

            ////有问题暂时这块先不设置此处的权限数据范围
            //if (!ManageProvider.Provider.Current().IsSystem)
            //{
            //    WhereSql.Append(" And (Id In (Select ResourceId From Sys_DataScopePermission Where");
            //    WhereSql.Append(" ObjectId IN ('" + ManageProvider.Provider.Current().ObjectId.Replace(",", "','") + "') ");
            //    WhereSql.Append(" ) )");
            //}
            WhereSql.Append(" ORDER BY Code,SortCode ASC");
            return Repository().FindList(WhereSql.ToString());
        }

        //public DataTable GetTable(ref JqGridParam jqgridparam)
        public DataTable GetTable(string CompanyId)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"Select  S.Id, 
                                    S.CompanyId,
                                    S.Code, 
                                    S.Expanded,
                                    S.ParentId, 
                                    S.Name, 
                                    S.[Level], 
                                    S.Lft, 
                                    S.Rgt, 
                                    S.KeyWords, 
                                    S.Url,
                                    S.PictureUrl,  
                                    D.FullName AS ShowMode,
                                    S.Style, 
                                    L.FullName AS Accesslimit,
                                    S.IsNav, 
                                    S.IsBlank, 
                                    S.SortCode, 
                                    S.CopyId, 
                                    S.CreateDate, 
                                    S.CreateUserId, 
                                    S.CreateUserName, 
                                    S.ModifyUserId, 
                                    S.ModifyDate, 
                                    S.ModifyUserName,
                                    S.AuditUserName
                              FROM Sites AS S 
                                   INNER JOIN 
                                  (SELECT DataDictionaryId, FullName, Code 
                                   FROM Sys_DataDictionaryDetail 
                                   WHERE (DataDictionaryId IN (SELECT DataDictionaryId FROM Sys_DataDictionary WHERE (Code = 'ShowMode')))
                                   ) AS D ON S.ShowMode = D.Code

                                  INNER JOIN 
                                  (SELECT DataDictionaryId, FullName, Code 
                                   FROM Sys_DataDictionaryDetail 
                                   WHERE (DataDictionaryId IN (SELECT DataDictionaryId FROM Sys_DataDictionary WHERE (Code = 'Accesslimit')))
                                   ) AS L ON S.Accesslimit = L.Code");
            if (!string.IsNullOrEmpty(CompanyId))
            {
                strSql.Append(" And S.CompanyId ="+"'" + CompanyId + "" + "' ");
            }
            strSql.Append(" ORDER BY Code,SortCode ASC");
            return DataFactory.Database().FindTableBySql(strSql.ToString());
            //strSql.Append(@"SELECT  * FROM  Sites Where 1=1");
            //return Repository().FindTablePageBySql(strSql.ToString(), null, ref jqgridparam);
        }
        /// <summary>
        /// 获取指定ParentId的List
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public List<Sites> GetList(int ParentId)
        {
            StringBuilder WhereSql = new StringBuilder();
            //if (!ManageProvider.Provider.Current().IsSystem)
            //{
            //    WhereSql.Append(" And (Id In (Select ResourceId From Sys_DataScopePermission Where");
            //    WhereSql.Append(" ObjectId IN ('" + ManageProvider.Provider.Current().ObjectId.Replace(",", "','") + "') ");
            //    WhereSql.Append(" ) )");
            //}
            WhereSql.Append(" And ParentId=" + ParentId + "");
            WhereSql.Append(" ORDER BY Code,SortCode ASC");
            return Repository().FindList(WhereSql.ToString());
        }

        public List<Sites> FindList()
        {
            return Repository().FindList();
        }

        public Sites GetEntity(int KeyValue)
        {
            return Repository().FindEntity(KeyValue);
        }
        #region 无限分级的递归Left和Right赋值操作
        int index = 1, Level = -1, i = 1;
        /// <summary>
        /// 无限分级的递归Left和Right赋值操作
        /// </summary>
        /// <param name="ParentId"></param>
        public void UpLR(int ParentId)
        {
            Level++;
            List<Sites> listData = GetList(ParentId);
            var sites = new Sites();
            foreach (var entity in listData)
            {
                sites.Id = entity.Id;
                sites.Lft = index;
                sites.Level = Level;
                sites.Code = i++;
                index++;
                UpLR(entity.Id);
                sites.Rgt = index;
                index++;
                DataFactory.Database().Update(sites);
            }
            Level--;
        }
        #endregion

        #region 递归删除栏目和子栏目
        public void DelRelated(int Id)
        {
            string delstr = "";
            var plist = Repository().FindList("ParentId", Id);
            foreach (var item in plist)
            {
                delstr += item.Id + ",";
                DelRelated(item.Id);
            }
            Repository().Delete(delstr.Split(',')); //批量删除         
        }
        #endregion

    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#存储过程调用的三个方法发布时间:2022-07-18
下一篇:
C#超简单自定义事件发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap