c# foreach loop iterations with list from query execution time

Viewed 655

this is marely an info I need.

When I do a foreach loop with C# iterating over a list as follows:

foreach (var record in DbContext.UserRecords.Where(record => record.UserId == user.Id &&
                                                                record.Date.Date == startDate.AddDays(i).Date)
                                                                .ToList())
{
    totHours += record.Hours;
}

what is happening exactly at every cycle? does the query happen again so I have N queries to the DB for each item in the list I want or it just does it the first time and then the loop keeps a temporary copy of the data? I'm trying to optimize times in my ASP.Net project and I was wondering if there was a cleaner/faster way to iterate these long data streams...

Thanks a lot!

1 Answers

No, you call ToList() on the IQueryable which executes the query and loads the data into memory.

Each iteration is then performed on an in-memory object.

Even without the ToList() the query would be executed once, and the data streamed from the database.

Whilst more memory efficient, this holds a lock on the underlying table for the duration of the loop, so you need to be cafeful with that approach.

Related