Legion
Legion

Reputation: 3437

Creating a queryable cached result from LINQ

I've got a view that's relatively small and I'd like to cache it after I fetch it from the DB. Since I only need certain rows based on userID, I'd rather not loop through my list of userIDs and query the database each time. I'd rather have the table in memory and then be able to perform linq queries against it to get the particular row I want.

var view = dbContext.view; //I know this line doesn't execute the query

for(int i = 0; i < userIDCount; i++)
{
    var dataRow = view.Where(v => v.userID == userIDs[i]);
}

Is there a way to keep view in memory and be able to use linq queries against it in the loop without hitting the DB over and over again?

Upvotes: 0

Views: 71

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180798

var view = dbContext.view.ToList();

will cache your view, by creating an in-memory IEnumerable. You can still run Linq queries against it.

However, consider putting the result in a Dictionary. It will be much faster to get rows by index.

Upvotes: 2

Related Questions