Can all 'for' loops be replaced with a LINQ statement?

前端 未结 7 524
逝去的感伤
逝去的感伤 2021-02-05 08:48

Is it possible to write the following \'foreach\' as a LINQ statement, and I guess the more general question can any for loop be replaced by a LINQ statement.

I\'m not i

7条回答
  •  伪装坚强ぢ
    2021-02-05 09:10

    In general yes, but there are specific cases that are extremely difficult. For instance, the following code in the general case does not port to a LINQ expression without a good deal of hacking.

    var list = new List>();
    foreach ( var cur in (new int[] {1,2,3})) {
      list.Add(() => cur);
    }
    

    The reason why is that with a for loop, it's possible to see the side effects of how the iteration variable is captured in a closure. LINQ expressions hide the lifetime semantics of the iteration variable and prevent you from seeing side effects of capturing it's value.

    Note. The above code is not equivalent to the following LINQ expression.

    var list = Enumerable.Range(1,3).Select(x => () => x).ToList();
    

    The foreach sample produces a list of Func objects which all return 3. The LINQ version produces a list of Func which return 1,2 and 3 respectively. This is what makes this style of capture difficult to port.

提交回复
热议问题