How to suppress VB's “Iteration variable shouldn't been used in lambda expression”

与世无争的帅哥 提交于 2019-12-12 08:53:51

问题


I'm working with LINQ in VB.NET and sometimes I get to a query like

For i = 0 To 10
  Dim num = (From n In numbers Where n Mod i = 0 Select n).First()
Next

and then it comes the warning "Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable."

I know it's not a good practice to use the iteration variable in the lambda expression, because lambda expressions are evaluated only when needed. (This question is about that)

Now my question is, how to suppress this warning in cases where the expression is evaluated in-place, with constructions like First(), Single(), ToList(), etc. (It's only a warning, but i like my code clean.)

(Declaring a local variable and passing the iteration variable to it is an option, but I'm looking for a clean solution.)


回答1:


In this particular case where the lambda is evaluated immediately, then you can safely eliminate the warning by moving the declaration of the iteration variable outside the for loop.

Dim i = 0
For i = 0 To 10 
 ...

I do want to stress though that this only works if the lambda does not escape the for loop (true for your scenario).

Also here is a detailed link to an article I wrote on this warning (why it exists, how to avoid it, etc ...)

  • http://blogs.msdn.com/b/jaredpar/archive/2007/07/26/closures-in-vb-part-5-looping.aspx


来源:https://stackoverflow.com/questions/3829571/how-to-suppress-vbs-iteration-variable-shouldnt-been-used-in-lambda-expressio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!