简体   繁体   English

IEnumerable.Contains()继续查询数据源而不是内存

[英]IEnumerable.Contains() keeps querying data source instead of memory

I have the following code to try and find a new unique value between 1000-10000 that I can assign to a userId. 我有以下代码尝试查找可以分配给userId的1000-10000之间的新唯一值。 I do this by querying the DB for all userIds and finding the first non-used one: 我通过查询数据库中的所有userId并找到第一个未使用的ID来做到这一点:

    var users = userDbContext.Data.Select(a => a.UserId);

    for (int i = 1000; i < 10000; i++)
    {
        if (!users.Contains(i))
        {
            this.Id = i;
            break;
        }
    }

For some reason, every iteration of this loop is querying the database table instead of just querying what's in memory. 由于某种原因,此循环的每次迭代都在查询数据库表,而不仅仅是查询内存中的内容。 Any idea how to solve this? 任何想法如何解决这个问题?

Hover the pointer over the var keyword and you'll see it's still an IQueryable<int> . 将指针悬停在var关键字上,您会看到它仍然是IQueryable<int>

You should turn this into a collection to process it in-memory, like so: 您应该将其转换为一个集合以在内存中进行处理,如下所示:

var users = userDbContext.Data.Select(a => a.UserId).ToList();

.ToList() will enumerate over the queryable, which will execute it. .ToList()将枚举可查询对象,它将执行它。

But you can do better: since you're mostly using Contains , use a HashSet where it's a O(1) operation: 但您可以做得更好:由于您主要使用Contains ,因此在HashSet (O)(1)操作中使用HashSet

var users = new HashSet<int>(userDbContext.Data.Select(a => a.UserId));

if you call ToList() or something similar to execute the query the data will be in memory. 如果调用ToList()或类似的命令来执行查询,则数据将在内存中。

The linq query isnt actually executed until it is needed. 直到需要时才实际执行linq查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM