Search code examples
vb.netlambdaextension-methodsanonymous-methods

Using List(Of T).ForEach method to update values not working as expected


I have the following code,

PB.ForEach(Function(x) x.Cost = GetPartCost(x.PartNumber, x.Units, x.Cost, FB))

Return PB.Sum(Function(x) (x.Cost * x.Qty))

However it always returns 0. I've checked and the GetPartCost function executes and returns a non-zero number but the list item cost properties are never updated.

The property is just a simple property,

Public Property Cost() As Double
    Get
        Return _Cost
    End Get
    Set(ByVal value As Double)
        _Cost = value
    End Set
End Property

If I set a breakpoint in the Set of the property, it never gets hit.

What is going on with this?


Solution

  • The problem here is your confusing comparison with assignment.

    Function(x) x.Cost = GetPartCost ...
    

    This compiles down to a comparison between x.Cost and GetPartCost not an assignment. The reason why is that Function (x) is an expression lambda and when used in the context of an expression = is comparison not assignment.

    To fix this use a statement / Sub to produce assignment semantics

    Sub(x) x.Cost = GetPartCost ...
    

    Note: Sub lambdas aren't available until Visual Studio 2010.