gpt4 book ai didi

asp.net - Linq 'contains' 查询耗时过长

转载 作者:行者123 更新时间:2023-12-04 23:06:48 26 4
gpt4 key购买 nike

我有这个查询:

var newComponents = from ic in importedComponents
where !existingComponents.Contains(ic)
select ic;
importedComponentsexistingComponents属于 List<ImportedComponent> 类型,并且只存在于内存中(不依赖于数据上下文)。在这种情况下, importedComponents有超过 6,100 项, existingComponents有 511 项。

这个语句完成的时间太长(不知道多长时间,我在 20 分钟后停止脚本)。我尝试了以下方法,但执行速度没有提高:
var existingComponentIDs = from ec in existingComponents
select ec.ID;

var newComponents = from ic in importedComponents
where !existingComponentIDs.Contains(ic.ID)
select ic;

任何帮助都感激不尽。

最佳答案

问题是该算法的二次复杂度。将所有现有组件ID 的ID 放入一个HashSet 并使用HashSet.Contains 方法。与列表中包含/任何内容的 O(N) 相比,它的查找成本为 O(1)。

morelinq项目包含一个方法,可以在一个方便的步骤中完成所有这些操作:ExceptBy。

关于asp.net - Linq 'contains' 查询耗时过长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10254619/

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