對於你們中的一些人來說,這可能看起來微不足道,但我對以下兩個例子感到困惑。LINQ通過局部變量
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
它更新我的價值,一切都很好了這一點。但是當我試圖更新數組的元素時,它不起作用。
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
您的代碼正常工作。您想做什麼? 'select ++ i;'不涉及你的數組。你只是增加我爲每個數字數組項目 –
令人困惑的部分是,我的值因「select ++ i」而改變,但num的值不是 – sotn