如何从一个有效的减少一个巨大的列表在C# [英] How to subtract one huge list from another efficiently in C#

查看:166
本文介绍了如何从一个有效的减少一个巨大的列表在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的Ids(整数)列表,代表我的数据库中的所有项目:

I have a very long list of Ids (integers) that represents all the items that are currently in my database:

var idList = GetAllIds();

我还有另一个巨大的通用列表,其中包含要添加到数据库的项目:

I also have another huge generic list with items to add to the database:

List<T> itemsToAdd;

现在,我想从通用列表中删除id已经在idList中的所有项目。
目前idList是一个简单的数组,我减去如下列表:

Now, I would like to remove all items from the generic list whose Id is already in the idList. Currently idList is a simple array and I subtract the lists like this:

itemsToAdd.RemoveAll(e => idList.Contains(e.Id));

我确定它可以更快,所以我应该使用两个集合的数据类型减去它们的最有效的做法是什么?

I am pretty sure that it could be a lot faster, so what datatypes should I use for both collections and what is the most efficient practice to subtract them?

谢谢!

推荐答案

> idList 到 HashSet< T> ,并使用相同的方法,即:

Transform temporarily idList to an HashSet<T> and use the same method i.e.:

items.RemoveAll(e => idListHash.Contains(e.Id));

应该会快很多

这篇关于如何从一个有效的减少一个巨大的列表在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆