BirnBaumBlüte BirnBaumBlüte - 4 months ago 40
Vb.net Question

Update values of a list using Linq

Is there a way of updating the values of a list(of some class) using a list(of string) using linq? For example, I got

Public class A
Public Property value As String
End Class

Public class B
Public Property AList As List(of A)
End Class


So i got a

Dim valueList As List(Of String)


and I want to set all the values of the AList as the values of valueList. For example given

valueList = {"A", "B", "C"}


I want

AList = { AClass1, AClass2, AClass3 }


where

AClass1.value = "A"
AClass2.value = "B"
AClass3.value = "C"

Answer

No, since LINQ is not meant to produce side effects

But you can do that with a simple for loop

Public Class A
    Public Property Value As String
End Class

Public Class B
    Public Sub Foo()
        Dim AList As New List(Of A)
        AList.Add(New A)
        AList.Add(New A)
        AList.Add(New A)
        Dim valueList As New List(Of String)
        valueList.Add("A")
        valueList.Add("B")
        valueList.Add("C")
        For i As Integer = 0 To AList.Count - 1
            AList(i).Value = valueList(i)
        Next
        AList.ForEach(Sub(a) Console.WriteLine(a.Value))
    End Sub
End Class

Outputs

A
B
C