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

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

相关推荐
jiayong2312 小时前
海量数据处理技术方案与实现原理
大数据·c#·linq
z落落16 小时前
C# 类与对象、字段、静态与非静态+四大访问修饰符
开发语言·c#
魔法阵维护师16 小时前
从零开发游戏需要学习的c#模块,第三十二章(Boss 战系统)
学习·游戏·c#
魔法阵维护师16 小时前
从零开发游戏需要学习的c#模块,第三十三章(暂停菜单)
学习·游戏·c#
z落落17 小时前
C# Stack栈 / Queue队列+所有集合 终极一页汇总(全覆盖、零遗漏)
java·开发语言·c#
淡海水18 小时前
08-认知篇-对比-injectfix深度解析
unity·c#·热更新·clr·hybrid·injectfix
周杰伦fans1 天前
C# 踩坑 CS8370:Switch Expression 在 C# 7.3 不可用及三种解决方案
c#
z落落1 天前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#
xiaoshuaishuai81 天前
C# AvaloniaUI动态显示图片
开发语言·c#