递归应用判断是否循环引用

cs 复制代码
var data = await _IDBInstance.DBOperation.QueryAsync<FormulaReference>(sql);

            //向上查询引用公式  
            List<FormulaReference> GetSonNode(long id, List<FormulaReference> nodeList, List<long> path = null)
            {
                if (path == null)
                {
                    path = new List<long>();
                }
                if (path.Contains(id))
                {
                    var formulaReferences = nodeList.Where(x => x.RefFormulaRecId == id);
                    _logger.Error("出现循环引用:" + id + "_数据:" + JsonConvert.SerializeObject(formulaReferences), null);
                    // 出现循环引用,抛出异常或返回空列表等
                    return new List<FormulaReference>();
                }
                path.Add(id);
                var query = nodeList.Where(c => c.RefFormulaRecId == id);
                var result = query.Concat(query.SelectMany(t => GetSonNode(t.FormulaRecId, nodeList, path))).ToList();
                path.Remove(id);
                return result;
            }
            var result = new List<FormulaReference>();
            foreach (var item in formulaRecIdList)
            {
                result.AddRange(GetSonNode(item, data.ToList()));
            }

代码中通过判断 path 列表是否包含当前的 id 来判断是否出现循环引用。如果 path 中已经包含了当前的 id,则表示在查询过程中出现了循环引用,会记录错误日志,并返回一个空的 FormulaReference 列表作为结果。这样可以避免在循环引用的情况下出现无限递归的情况,并及时处理循环引用的问题。

相关推荐
小码编匠2 小时前
.NET 10 性能突破:持续优化才是质变关键
后端·c#·.net
mudtools5 小时前
.NET驾驭Excel之力:Excel应用程序的创建与管理
c#·.net·excel·wps
mudtools5 小时前
.NET驾驭Excel之力:自动化数据处理 - 开篇概述与环境准备
c#·自动化·.net·excel·wps
唐青枫5 小时前
C#.NET WebAPI 返回类型深度解析:IActionResult 与 ActionResult<T> 的区别与应用
c#·.net
William_cl14 小时前
C# ASP.NET MVC 数据验证实战:View 层双保险(Html.ValidationMessageFor + jQuery Validate)
后端·c#·asp.net·mvc
狮子不白15 小时前
C#WEB 防重复提交控制
开发语言·前端·程序人生·c#
Charles_go17 小时前
C#8、有哪些访问修饰符
java·前端·c#
yue00818 小时前
C# 求取整数的阶乘
java·开发语言·c#
黑咩狗夜.cm20 小时前
Aspose.word实现表格每页固定表头、最后一行填满整个页面
开发语言·c#·word
code bean20 小时前
【C#笔记】Newtonsoft.Json 中 `[JsonIgnore]` 的作用详解
笔记·c#·json