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

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 列表作为结果。这样可以避免在循环引用的情况下出现无限递归的情况,并及时处理循环引用的问题。

相关推荐
李高钢17 小时前
C# WinForms 架构与项目实战:多窗体通信、三层架构、数据库、日志与配置
架构·c#·winforms
OPEN-F20 小时前
Python进阶教程:自动化办公实战
python·c#·自动化
czhc114007566321 小时前
C# 处理体数据:装、钉、交、取消
c#
淡海水21 小时前
03-03-线性-LinkedList-T-源码不变式与选择边界
windows·链表·c#·编译·linkedlist·clr·机器码
longxiaozhang62 天前
C# Array类:数组其实没那么难
开发语言·c#
longxiaozhang62 天前
C#运算符重载:让对象也能使用“加减乘除”
开发语言·c#
花落人散处2 天前
C# 核心编程知识点总结:网络编程、委托与事件、异步编程与LINQ
c#
fl1768312 天前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
CoderIsArt2 天前
OPC UA 完整介绍、官网、C# 简单使用
开发语言·c#
界面开发小八哥2 天前
界面控件DevExpress XAF v26.1新版亮点——AI Agent Skills
ai·c#·跨平台·devexpress·ui开发·xaf