Accepted answer

the statements are, in this case, semantically the same as select (and linq in general) uses deferred execution of delegates. it won't run any declared queries until the result is being materialised, and depending on how you write that query it will do it in proper sequence.

a very simple example to show that:

var list = new list<string>{"hello", "world", "example"};

func<string, string> func = (s) => {
    return s.toupper();

foreach(var item in => func(i)))

results in



the execution will be deferred meaning they will have the same exec


select uses deferred execution. this means that it will, in order:

  • take an item from rows
  • call _executefunc on it
  • call runstoredprocedure on the result of _executefunc

and then it will do the same for the next item, until all the list has been processed.


in the top example, using select will project the rows, by yielding them one by one.


foreach (var result in => _executefunc(row)))

is basically the same as

foreach(var row in rows)

thus select is doing something like this

for each row in source
   result = _executefunc(row)
   yield result

that yield is passing each row back one by one (it's a bit more complicated than that, but this explanation should suffice for now).

if you did this instead

foreach (var result in => _executefunc(row)).tolist())

calling tolist() will return a list of rows immediately, and that means _executefunc() will indeed be called for every row, before you've had a chance to call runstoredprocedure().

thus what resharper is suggesting is valid. to be fair, i'm sure the jetbrains devs know what they are doing :)


in your first example, _executefunc(row) will not be called first for each item in rows before your foreach loop begins. linq will defer execution. see this answer for more details.

the order of events will be:

  1. evaluate the first item in rows
  2. call executefunc(row) on that item
  3. call runstoredprocedure(result)
  4. repeat with the next item in rows

now, if your code were something like this:

foreach (var result in => _executefunc(row)).tolist())

then it would run the linq .select first for every item in rows because the .tolist() causes the collection to be enumerated.

Related Query

More Query from same tag