SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Development resources, articles, tutorials, code samples, tools and downloads for AWS Amazon Web Services, Redshift, AWS Lambda Functions, S3 Buckets, VPC, EC2, IAM


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.

Using the iteration variable in a lambda expression may have unexpected results

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

Code




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

Code

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.



AWS


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.