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

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

相关推荐
leo__52011 小时前
C# 虚拟键盘(软键盘)实现
单片机·c#·计算机外设
周杰伦fans12 小时前
AutoCAD C# 二次开发:如何精确监听工作空间切换事件
前端·c#
用户37215742613513 小时前
如何使用 C# 自动调整 Excel 行高和列宽
c#
AI导出鸭PC端13 小时前
智谱清言怎么生成word文档?AI导出鸭终结乱码烦恼
人工智能·ai·c#·word·豆包·ai导出鸭
xiaoshuaishuai814 小时前
C# AvaloniaUI 中旋转
开发语言·c#
weixin_4280053015 小时前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第9天实战-实现计算器工具
开发语言·学习·c#·functioncalling·ai实现计算器工具
guygg8815 小时前
基于C# + Halcon的通用ROI绘制工具
stm32·单片机·c#
双河子思16 小时前
《代码整洁之道》——读书笔记(持续更新)
开发语言·c++·c#
诙_16 小时前
unity——C#
unity·c#·游戏引擎
cici1587416 小时前
C# LAS 点云读取与处理工具
stm32·单片机·c#