c# – 在递归方法中使用LinqToSql对性能非常不利

我有以下方法使用 LinqTosql获取节点的所有父节点,但我不知道它对性能有多大影响.

来自NodeTable:

public partial class Node   
{
    public List<Node> GetAllParents(IEnumerable<Node> records)
    {
        if (this.ParentID == 0)
        {
            // Reach the parent,so create the instance of the collection and brake recursive.
            return new List<Node>();
        }

        var parent = records.First(p => p.ID == ParentID);

        // create a collection from one item to concat it with the all parents.
        IEnumerable<Node> lst = new Node[] { parent };

        lst = lst.Concat(parent.GetAllParents(records));

        return lst.ToList();
    }
}

好吗 !!或任何改善它的想法!

谢谢.

解决方法

因此,上面的代码是向上(父)方向的父子层次结构.因此,在最坏的情况下,它将导致对数据库的n层次深度进行n次查询.我建议你稍微改变方法来尝试延迟执行

public IEnumerable<Node> GetAllParents(IEnumerable<Node> records)
{
        if (this.ParentID == 0)
        {
            // Reach the parent,so create the instance of the collection and brake recursive.
            return new List<Node>();
        }

        var parent = records.Where(p => p.ID == ParentID);
        var parents = parent.Concat(parent.GetAllParents(records));

        return parent;
}

我不是100%确定它是否可行但是想法是利用表达式树/延迟执行,以便在单个数据库之旅中触发多个查询.

一个想法是编写一个存储的proc / view,它将返回所有父节点(在sql server中查看相同的CTE).

编辑:使用Where而不是First在上面的代码中查找parent,因为First肯定会立即进行评估 – (警告:仍然未经测试的代码)

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...