Using the iteration variable in a lambda expression may have unexpected results.
While working on an ASP.NET project, I had faced with the warning message of Microsoft Visual Studio 2008 within a code I had built using FOR LOOP.
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 iteration variable.
Here is the original VB.NET code block which is causing the warning message :
Dim listForContexts As New List(Of ZTW_Context_CallInfo)
For i As Integer = 0 To dicForAuthorizedServices.Keys.Count - 1
If Me.m_Model.ReturnObjOfAuthorizedServices IsNot Nothing Then
listForContexts.AddRange(Me.m_Model.ReturnObjOfAuthorizedServices.Where(Function(x) x.AuthorizedService IsNot Nothing AndAlso x.AuthorizedService.Phone IsNot Nothing AndAlso x.AuthorizedService.Phone = dicForAuthorizedServices.Keys(i)).Select(Function(y) y.Context).ToList())
authorizedServicesBindingObject.Add(New Object() {listForContexts, dicForAuthorizedServices.Values(i)})
End If
Next
Solution :
And below the corrected VB.NET code which eliminates the possible error caused by using the iteration variable in a lambda expression.
Dim listForContexts As New List(Of ZTW_Context_CallInfo)
For i As Integer = 0 To dicForAuthorizedServices.Keys.Count - 1
Dim ii As Integer = i
If Me.m_Model.ReturnObjOfAuthorizedServices IsNot Nothing Then
listForContexts.AddRange(Me.m_Model.ReturnObjOfAuthorizedServices.Where(Function(x) x.AuthorizedService IsNot Nothing AndAlso x.AuthorizedService.Phone IsNot Nothing AndAlso x.AuthorizedService.Phone = dicForAuthorizedServices.Keys(ii)).Select(Function(y) y.Context).ToList())
authorizedServicesBindingObject.Add(New Object() {listForContexts, dicForAuthorizedServices.Values(ii)})
End If
Next
You can easily notice that I added a new variable (ii) as the warning message suggests.
Within the loop the initial value of the new variable is equals to the iteration value.
Then within the VB.NET For Loop code I replaced the iteration parameter with the new variable.