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

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

相关推荐
玩泥巴的4 小时前
.NET 8+ 飞书API实战:自动化群组管理与消息推送
c#·.net·二次开发·飞书
烛阴4 小时前
从`new`关键字开始:精通C#类与对象
前端·c#
yangshuquan5 小时前
使用 C# + IronOcr,轻松实现图片文字自动识别(OCR)和提取
c#·ocr·编程技巧·winforms
天天代码码天天5 小时前
TSR18测速雷达C#对接
c#·雷达测速·tsr18测速雷达
道一235 小时前
C#获取操作系统版本号方法
开发语言·c#
道一235 小时前
C# 判断文件是否存在的方法
开发语言·c#
唐青枫6 小时前
C#.NET 范围与索引(Range、Index)完全解析:语法、用法与最佳实践
c#·.net
矶鹬笛手13 小时前
(2.1) 信息技术及其发展
sql·计算机网络·c#
u***276114 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
笑非不退16 小时前
C# c++ 实现程序开机自启动
开发语言·c++·c#