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

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

相关推荐
Scout-leaf16 小时前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m62518 小时前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech1 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072552 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
m0_547486662 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
叶帆2 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
IT方大同2 天前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落2 天前
C# FileStream文件流读取文件
开发语言·c#
yngsqq2 天前
排版优化 异形排版
c#
苦学的罐头2 天前
C# 协变与逆变深度解析:为什么 IEnumerable<T> 能转换,而 List<T> 不行?
开发语言·c#·list