so wondering whether using linq where clause in foreach loop means on each iteration re-evaluate linq where clause. example:
var myid = 1; foreach (var thing in listofthings.where(x => x.id == myid)) { //do } or better write:
var myid = 1; var mylist = listofthings.where(x => x.id == myid); foreach (var thing in mylist) { //do } or both work in same way?
this sample should give answers seek:
code
using system; using system.linq; public class test { public static void main() { // create sequence of integers 0 10 var sequence = enumerable.range(0, 10).where(p => { // in each 'where' clause, print current item. // shows when clause executed console.writeline(p); // make sure every value selected return true; }); foreach(var item in sequence) { // print marker show when loop body executing. // helps see if 'where' clauses evaluated // before loop starts or during loop console.writeline("loop body exectuting."); } } } output
0 loop body exectuting. 1 loop body exectuting. 2 loop body exectuting. 3 loop body exectuting. 4 loop body exectuting. 5 loop body exectuting. 6 loop body exectuting. 7 loop body exectuting. 8 loop body exectuting. 9 loop body exectuting. conclusion
the where clause evaluated once, current element, @ start of each loop iteration.
Comments
Post a Comment