0

Sorry if I misexpain in title,

What I want to ask is easy to say via code below;

var userList = context.Where(w=> w.age > 20);

foreach(var item in userList.ToList())
{
  ...
}

userList.ToList() retrieves 100 rows

I wonder if 'userList.ToList()' fires 100 times, (each iteration and go to database to retrieve records)

or just once and iterate the original collection.

It seems weird but now super important for me since my colleague claim it knock to db 100 times and I believe it does once..

1 Answers1

1

It will call database one time, you even don't need ToList there. The easiest way to check it - just use database profiler and see queries which will hit it. foreach is translated by compiler into something like that:

    IEnumerator<EntityType> enumerator = queryable.GetEnumerator();
    try
    {
        while (enumerator.MoveNext())
        {
            EntityType current = enumerator.Current;
        }
    }
    finally
    {
        if (enumerator != null)
        {
            enumerator.Dispose();
        }
    }

So you are working with the same Enumerator and it does not makes sense to call db multiple times.

Also if your colleague statement about userList.ToList() being fired 100 times the next should have written to console multiple times:

IEnumerable<int> GetEn()
{
    Console.WriteLine(nameof(GetEn));
    foreach (var element in new[] {10,20,30})
    {
        yield return element;
    }
}

var userList = GetEn().Where(w => w > 20);  
foreach (var item in userList.ToList())
{
    
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132