Slow foreach() on a LINQ query - ToList() boosts performance immensely - why is this?

前端 未结 3 1837
猫巷女王i
猫巷女王i 2021-01-04 07:59

I kind of grasp the whole delayed execution concept, but the following has me puzzled...

On a DataTable containing about 1000 rows, I call AsEnumerable(). I

3条回答
  •  余生分开走
    2021-01-04 08:15

    You don't understand which methods are deferred and which are not, so you don't understand when your code defines operations vs performs operations.

    These are all deferred. They define, but do not execute, an operation.

    source.AsEnumerable
    source.Select
    source.Where
    

    These enumerate the source and so are not deferred.

    source.ToList
    source.First
    source.Single
    foreach(var x in source)
    

提交回复
热议问题