Performance 正在查找不在DB中的字符串

Performance 正在查找不在DB中的字符串,performance,linq,optimization,Performance,Linq,Optimization,我的应用程序中有一些糟糕的性能问题。其中一个大的操作是比较字符串。 我下载了一个字符串列表,大约1000-10000。这些都是唯一的字符串。 然后我需要检查数据库中是否已经存在这些字符串。 我使用的linq查询如下所示: IEnumerable<string> allNewStrings = DownloadAllStrings(); var selection = from a in allNewStrings where !(from o in

我的应用程序中有一些糟糕的性能问题。其中一个大的操作是比较字符串。 我下载了一个字符串列表,大约1000-10000。这些都是唯一的字符串。 然后我需要检查数据库中是否已经存在这些字符串。 我使用的linq查询如下所示:

IEnumerable<string> allNewStrings = DownloadAllStrings();

var selection = from a in allNewStrings
                where !(from o in context.Items
                        select o.TheUniqueString).Contains(a)
                select a;
IEnumerable AllNewString=downloadAllString();
var selection=来自AllNewString中的
哪里(来自上下文中的o.Items)
选择o.TheUniqueString)。包含(a)
选择一个;
我是否做错了什么,或者我如何让这个过程更快(最好是使用Linq)


谢谢。

您确实为
所有新闻字符串中的每个元素查询了相同的唯一字符串1000-10000次,因此效率极低

尝试单独查询唯一字符串,以便执行一次:

IEnumerable<string> allNewStrings = DownloadAllStrings();

var uniqueStrings = from o in context.Items
                    select o.TheUniqueString;

var selection = from a in allNewStrings
                where !uniqueStrings.Contains(a)
                select a;

另一种解决方案是使用
哈希集

var set = new HashSet<string>(DownloadAllStrings());
set.ExceptWith(context.Items.Select(s => s.TheUniqueString));
var set=newhashset(DownloadAllStrings());
set.ExceptWith(context.Items.Select(s=>s.TheUniqueString));

集合现在将包含数据库中不存在的字符串。

Except()
将比
具有更好的性能!Contains()
@Magnus:是的,Set运算符比序列上的成员测试更有效。我更新了答案,以便更清楚地说明。感谢您提供了这个伟大的解决方案。我最初唯一关心的是它现在工作得很好,但是当我有100万个项目的帖子,需要将它们全部“下载”到内存中,然后进行比较时,会发生什么呢?这种方法对于大量的
uniquestring
来说仍然是合理的,假设您有大量内存来避免缓存丢失。
var set = new HashSet<string>(DownloadAllStrings());
set.ExceptWith(context.Items.Select(s => s.TheUniqueString));