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

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

相关推荐
czhc11400756633 分钟前
插补、另存为、标记过滤、采集超时——今天聊的四件事
c#
小羊没烦恼!1 小时前
Memory 记忆设计讨论:Agent Memory 的数据模型可以怎么设计
java·开发语言·前端·c++·c#
小羊没烦恼!5 小时前
Memory 记忆设计讨论:为什么 Agent Memory 不能只靠向量数据库?
java·开发语言·windows·算法·c#
...6225 小时前
C# 中 Lambda 表达式的全面讲解
c#
...6227 小时前
WinForm中Socket通信服务端客户端代码实现讲解
tcp/ip·c#·socket
唐青枫1 天前
别只会看日志:C#.NET SOS 调试扩展从 Dump 到内存泄漏排查
c#·.net
yswenli1 天前
基于C#开发网站视频嗅探下载工具——BrowserVideoGrabber
c#·videodownload·webvideodownload·videograbber
Lost of 程序猿1 天前
M2 实战:询价与采购订单聚合落地——跨聚合一致性、领域事件与 Outbox
开发语言·c#·asp.net·.net
Polevne1 天前
C# GRPC 一元与双向流
linux·算法·c#
XiaoZhenHua982 天前
C#工业机器视觉Recipe配方系统设计:多型号、多相机、多工位参数如何统一管理
c#·软件架构·机器视觉·工业自动化·工业软件·recipe