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

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

相关推荐
ctrl_v助手38 分钟前
C#表达题笔记
开发语言·c#
geovindu2 小时前
CSharp: Dijkstra Algorithms
开发语言·后端·算法·c#
公子小六3 小时前
基于.NET的Windows窗体编程之WinForms图像控件
windows·microsoft·c#·.net·winforms
吴可可1233 小时前
C# CAD自定义图元优化切割路径
c#
Lucky_Turtle5 小时前
【论文写作】PDF图片不清晰,打印生成PDF空白大,PDF字体嵌入
开发语言·pdf·c#
落寞的星星16 小时前
这个对象就包含了已经转换好的DFA和各种词法分析器运转所需要的参数。下一步,我们就可以用ScannerInfo对象创建出Scanner对象,请看下面的代码:
开发语言·c#
聪慧的水蜜桃20 小时前
【YFIOs】用C#开发硬件之设备上云
开发语言·c#
hixiong1231 天前
TensorRT转换工具分享
人工智能·计算机视觉·ai·c#
莫生灬灬1 天前
DY联系人聊天Web面板支持获取联系人/聊天记录/发送消息
前端·chrome·websocket·c#
逝水无殇1 天前
C# 多态性详解
开发语言·后端·c#