score:4

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) => {
    console.writeline(s);
    return s.toupper();
};

foreach(var item in list.select(i => func(i)))
{
    console.writeline(item);
}

results in

hello
hello
world
world
example
example

score:1

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

score:2

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.

score:3

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

so

foreach (var result in rows.select(row => _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 rows.select(row => _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 :)

score:4

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 rows.select(row => _executefunc(row)).tolist())
{                   
   runstoredprocedure(result)
}

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