加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – Linq’包含’查询耗时太长

发布时间:2020-12-16 07:23:37 所属栏目:asp.Net 来源:网络整理
导读:我有这个问题: var newComponents = from ic in importedComponents where !existingComponents.Contains(ic) select ic; importedComponents和existingComponents的类型为List ImportedComponent,并且仅存在于内存中(不依赖于数据上下文).在这种情况下,imp
我有这个问题:

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

importedComponents和existingComponents的类型为List< ImportedComponent>,并且仅存在于内存中(不依赖于数据上下文).在这种情况下,importedComponents只有超过6,100个项目,而现有组件有511个项目.

这句话花了太长时间才完成(我不知道多久,我在20分钟后停止了剧本).我尝试了以下但没有提高执行速度:

var existingComponentIDs = from ec in existingComponents
                           select ec.ID;

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

任何帮助都感激不尽.

解决方法

您可以使用 Except来获得设置差异:

var existingComponentIDs = existingComponents.Select(c => c.ID); 
var importedComponentIDs = importedComponents.Select(c => c.ID);
var newComponentIDs = importedComponentIDs.Except(existingComponentIDs);
var newComponents = from ic in importedComponents
        join newID in newComponentIDs on ic.ID equals newID
        select ic;
foreach (var c in newComponents)
{ 
    // insert into database?
}

Why is LINQ JOIN so much faster than linking with WHERE?

简而言之:Join方法可以设置一个哈希表,用作索引来快速将两个表拉链在一起

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读