gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:18:15 25 4
gpt4 key购买 nike

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

来自节点表:

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();
}
}

好吃吗!!或任何改进它的想法!!

谢谢。

最佳答案

因此,上面的代码是在向上( parent 的)方向上走父子层次结构。所以在最坏的情况下,它会导致对数据库进行 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% 确定它是否有效,但我的想法是利用表达式树/延迟执行,以便在单个数据库行程中触发多个查询。

另一个想法是编写一个存储过程/ View ,它将返回所有父级(查看 sql server 中的 CTE 是否相同)。

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

关于c# - 在递归方法中使用 LinqToSql 对性能非常不利,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4815021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com