ashishduh
ashishduh

Reputation: 6699

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. I do this by querying the DB for all userIds and finding the first non-used one:

    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?

Upvotes: 0

Views: 73

Answers (2)

Lewis Taylor
Lewis Taylor

Reputation: 728

if you call ToList() or something similar to execute the query the data will be in memory.

The linq query isnt actually executed until it is needed.

Upvotes: 1

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

Hover the pointer over the var keyword and you'll see it's still an 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.

But you can do better: since you're mostly using Contains, use a HashSet where it's a O(1) operation:

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

Upvotes: 10

Related Questions