1

如何更改对象列表中 1 个(或多个)指定项的 1 个属性

Class Item
    Private _Id As Integer
    Private _Value As Boolean 'can be string, int , .....

    Public Property Id() As Integer
        Get
            Return _Id
        End Get
        Set(ByVal value As Integer)
            _Id = value
        End Set
    End Property
    Public Property Value() As Boolean
        Get
            Return _Value
        End Get
        Set(ByVal value As Boolean)
            _Value = value
        End Set
    End Property

    Public Sub New(ByVal id As Integer, ByVal value As Boolean)
        Me.Id = id
        Me.Value = value
    End Sub       
End Class

...

Dim lst As New List(Of Item)
lst.Add(New Item(1, True))
lst.Add(New Item(2, True))
lst.Add(New Item(3, True))

lst = from l in lst select l ' and change the value of the element 2 to FALSE

结果

之前的列表

Item
[_Id = 1] 
[_Value = True] 

Item
[_Id = 2] 
[_Value = True] 

Item
[_Id = 3] 
[_Value = True] 

之后列出

Item
[_Id = 1] 
[_Value = True] 

Item
[_Id = 2] 
[_Value = False] 

Item
[_Id = 3] 
[_Value = True] 
4

1 回答 1

1

Linq 用于查询而不是更新。要更新使用传统循环和/或索引器:

l(2).Value = false

或者,如果您想使用 Linq 来确定要更改对象,只需循环查询结果:

Dim query = From l In lst Where l.Id = 2 Select l
For Each l In query
   l.Value = false
Next l

或者,因为您只期望一项:

Dim query = From l In lst Where l.Id = 2 Select l
query.Single().Value = False

然后,您的原始列表将具有更新的项目,因为列表和查询包含对项目的引用

但是,如果您想要一个Item值略有不同的 NEW 列表,那么这是可能的:

Dim query = From l In lst _
            Select New Item With { _ 
               ID = l.ID, _
               Value = IIf(l.ID = 2, False, l.Value) _
            } 

但请注意,这会创建 NEW Items,它不会修改Item存储在原始列表中的现有 s。

于 2013-01-31T16:06:12.343 回答