简体   繁体   English

这两段代码有什么区别?

[英]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;
for (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};
for (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 is 10,15,20,25,30 and the second one's is 30. I'm a little confused about the difference between int x; 第一个seq的最终值是10,15,20,25,30,第二个是30.我对int x;之间的区别感到有点困惑int x; and int y = div[i]; int y = div[i]; . Can someone explain this to me? 谁可以给我解释一下这个?
Thanks! 谢谢!

Invoking seq = seq.Where( s=> s%x ==0); 调用seq = seq.Where( s=> s%x ==0); does not iterate over elements. 不会迭代元素。 It only creates an IEnumarable encapsulating the iteration, that can be iterated in fututre. 它只创建一个封装迭代的IEnumarable ,可以在fututre中迭代。

So if you declare your x variable before the loop, the lambda, that you passed in Where() uses the same variable. 因此,如果在循环之前声明x变量,则在Where()传递的lambda使用相同的变量。 Since you are changing its value in a loop, eventually only the last one will be actually 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);

The result is different because you are using lambda expression in the LINQ's Where() parameter. 结果是不同的,因为您在LINQ的Where()参数中使用lambda表达式。 The actual execution of the all lambdas in Where() 's is performed on the very last row of both examples - the line where you perform .ToList() . Where()所有lambdas的实际执行是在两个示例的最后一行 - 您执行的行.ToList()执行的。 Have a look at the Variable Scope in Lambda Expressions 看看Lambda表达式中的变量范围

The difference in the examples is how you initialize x/y . 示例中的差异在于如何初始化x/y

In the first example there is only one memory slot for the variable x regardless of number of iterations of the foreach . 在第一个例子中,变量x只有一个存储器槽,而不管foreach的迭代次数。 The x always points to the same spot in the memory. x始终指向内存中的相同位置。 Therefore there is only one value of the x on the last row and it is equal to the div[2] . 因此,最后一行只有一个x值,它等于div[2]

In the second example there is separate memory slot created for y in each iteration of the loop. 在第二个例子中,在循环的每次迭代中为y创建了单独的存储器槽。 As the program evaluates, the address where y points to is changed in every iteration of the foreach . 在程序评估时, y指向的地址在foreach每次迭代中都会发生变化。 You might imagine it as there are multiple y variables like y_1 , y_2 ,... Hence when evaluating the actual lambdas in Where() s the value of the y is different in every one of them. 您可能会想象它有多个y变量,如y_1y_2 ,......因此,当评估Where()的实际lambda时, y的值在每个变量中都是不同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM