Problems with Linq using anonymous type
Why did the anonymous type property "Points" still have the value "0"?
Public Class Test
Public Su开发者_Python百科b New(ByVal _ID As Integer)
ID = _ID
End Sub
Public ID As Integer
End Class
Dim list As New List(Of Test)
list.Add(New Test(1))
list.Add(New Test(2))
list.Add(New Test(3))
Dim query = From X In list Select New With {.Points = 0, X.ID}
For Each o In query
o.Points = 1
Next
Because your query
variable actually represents a query, not an actual set of data. Every time you enumerate over query
it will perform the action again; your declaration (assigning the query
variable) defines the query. Enumerating it executes it. What it looks like you want to do is create an in-memory representation of the query in the form of a list. You can do something like this:
Dim list = (From X In list Select New With {.Points = 0, X.ID}).ToList()
For Each o In list
o.Points = 1
Next
This should give you the behavior you're expecting.
精彩评论