对于你们中的一些人来说,这可能看起来微不足道,但我对下面的这两个例子感到困惑。
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int i = 0;
var simpleQuery =
from num in numbers
select ++i;
foreach (var item in simpleQuery)
{
Console.WriteLine("v = {0}, i = {1}", item, i); // now i is incremented
}
输出:
v = 1, i = 1
v = 2, i = 2
v = 3, i = 3
v = 4, i = 4
v = 5, i = 5
v = 6, i = 6
v = 7, i = 7
v = 8, i = 8
v = 9, i = 9
v = 10, i = 10
它更新了 i 的值,到目前为止一切都很好。但是当我尝试更新数组的元素时,它就不起作用了。
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var simpleQuery =
from num in numbers
select ++num;
int i = 0;
foreach (var item in simpleQuery)
{
Console.WriteLine("v = {0}, num = {1}", item, numbers[i++]); // now num is NOT incremented???
}
输出:
v = 6, num = 5
v = 5, num = 4
v = 2, num = 1
v = 4, num = 3
v = 10, num = 9
v = 9, num = 8
v = 7, num = 6
v = 8, num = 7
v = 3, num = 2
v = 1, num = 0
这背后的原因可能是什么?
编辑: 我认为第二个示例将输出:
v = 6, num = 6
v = 5, num = 5
v = 2, num = 2
v = 4, num = 4
v = 10, num = 10
v = 9, num = 9
v = 7, num = 7
v = 8, num = 8
v = 3, num = 3
v = 1, num = 1