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 Kodyaz Development Resources
Development resources, articles, tutorials, samples, codes and tools for .Net, SQL Server, Windows, Windows Phone, SAP and ABAP, like SAP UI5, Screen Personas, etc.






.NET Framework, ASP.NET

ASP.NET, Windows Forms, Controls, .NET Framework and Visual Studio Articles

ASP.NET Forums

Visual Studio Forums

.NET Development Blog

Certification Exams Blog




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





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.












Copyright © 2004 - 2017 Eralper YILMAZ. All rights reserved.
Community Server by Telligent Systems