philmckendry
philmckendry

Reputation: 565

Linq statement only executing once and returning zero on second try and above in foreach loop

Hi I have a piece of code to gather the price of a selection in an observable collection and perform some operations with it via a loop. The code is shown below.

      Dim listOfSelectionNames = GameBetCreator.SelectedNumbersString.Split(",")

        For Each selection In listOfSelectionNames
            Dim currentSelection = selection

            Dim price = (From sels In Market.Selections
                               Where sels.Name = currentSelection Select sels.Price).FirstOrDefault()

            Dim returns = (price * omrStake1.UnitStake) + omrStake1.UnitStake

            potentialReturnStringBuilder.AppendLine("Selection " + currentSelection + " Returns " + returns.ToString())

        Next

The variable price is an int and market is a static variable and will never be null. On the first increment within the loop the code works ok and pulls back a value, however every time after that the variable price is set to zero once it hits the linq statement. Before that the price variable keeps the value from the previous loop (no idea why).

I have tried to replace the linq with a foreach loop looping through all the selections in Market.Selections and do an if statement to check whether the name in that matched the currentSelection but it produces the same result. As far as I can see the code should work everytime so im at a loss here. Any guidance will be appreciated

EDIT - SOME EXAMPLES AS REQUESTED

listOfSelectionNames = "1", "4", "ODD", "1-12"

Market.Selections

  1. name= "ODD" price=2

  2. name="1" price=36

  3. name="4" price=36

  4. name= "1-12" price=12

Note there will never be a scenario where the listOfSelectionNames will contain a value that does not have a corresponding selection.name in the Market.Selections list

Upvotes: 0

Views: 61

Answers (1)

philmckendry
philmckendry

Reputation: 565

The issue is that the variable name had a setter that trimmed the whitespace If String.IsNullOrEmpty(value) = False Then strName = value.Trim which meant I had to do the same when passing currentSelection into the linq statement.

Therefore the code would look like this

 Dim price = (From sels In Market.Selections
                           Where sels.Name = currentSelection.Trim() Select sels.Price).FirstOrDefault()

This is posted simply to help others who may have encountered the same problem

Upvotes: 1

Related Questions