开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜