c# - What is the difference between these two pieces of code? -


int[] div = new int[] {2,3,5}; ienumerable<int> seq = new int[] {10,15,20,25,30}; int x; (int i=0; i<div.length; i++){   x = div[i];   seq = seq.where( s=> s%x ==0); } seq = seq.tolist(); 

and

int[] div = new int[] {2,3,5}; ienumerable<int> seq = new int[] {10,15,20,25,30}; (int i=0; i<div.length; i++){   int y = div[i];   seq = seq.where( s=> s%y ==0); } seq = seq.tolist(); 

the first seq's final value 10,15,20,25,30 , second one's 30. i'm little confused difference between int x; , int y = div[i]; . can explain me?
thanks!

invoking seq = seq.where( s=> s%x ==0); not iterate on elements. creates ienumarable encapsulating iteration, can iterated in fututre.

so if declare x variable before loop, lambda, passed in where() uses same variable. since changing value in loop, last 1 used.

instead of expression like:

seq.where( s=> s % 2 == 0).where( s=> s % 3 == 0).where( s=> s % 5 == 0); 

you get:

seq.where( s=> s % 5 == 0).where( s=> s % 5 == 0).where( s=> s % 5 == 0); 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -