linq vb.net change value



如何更改对象列表中 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] 

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的列表,那么这是可能的:

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

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

相关内容

  • 没有找到相关文章

最新更新