これは些細なことのように思えるかもしれませんが、以下の 2 つの例について私は混乱しています。
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
この背後にある理由は何でしょうか?
編集: 2番目の例は次のように出力されると思いました:
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