LINQ Query - Explanation needed of why these examples are different

前端 未结 2 1737
醉酒成梦
醉酒成梦 2021-02-15 16:50

I\'m reading the book \"LINQ Pocket Reference\" and there is a particular example (slightly modified below) that I\'m having difficulty getting my head around... The explanation

2条回答
  •  没有蜡笔的小新
    2021-02-15 17:33

    Actually, with rereading it, it makes sense. Using the temp variable means that the temp itself is captured within the query... We are evaluating the loop five times, and therefore there are five instantiated temp variable references for each version of the query.

    In the case without the temp variable, there is only the reference to the loop variable.

    So five references versus one reference. That's why it produces the results as shown.

    In the first case, once it's evaluated the loop totally, the query has used the five references to the temp variables, hence stripping out a, e, i, o and u respectively.

    In the second case, it's doing the same thing... only all five references are to the same variable which obviously only contains one value.

    Moral of the story: Think "reference" not "value".

    So, does this make sense to anyone else now?

提交回复
热议问题