1

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"
itsme86
  • 19,266
  • 4
  • 41
  • 57
  • 1
    Do you want to generate a new list for `AList` or do you want to update already existing elements in that list? Note that the latter is the opposite of what LINQ is made for. LINQ is for querying from sets, it's not for side effects or changing values in a set. – René Vogt Aug 03 '16 at 15:48
  • You have a List so you can use List.ForEach. Specifically using LINQ is not recommended: http://stackoverflow.com/a/200614/832052 – djv Aug 03 '16 at 16:01
  • thanks. I'm still new to Linq and not really familiar with what it can and cannot do.. – BirnBaumBlüte Aug 03 '16 at 18:40

1 Answers1

1

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

Note:

The .ForEach extension is a member of List<T>, and not IEnumerable<T>, which is what is available in LINQ. For a complete list of what you can do with LINQ, see https://msdn.microsoft.com/en-us/library/system.linq.enumerable(v=vs.110).aspx

Technically, you can use LINQ expressions to accomplish a similar thing. But it is just a way to get around the guideline that LINQ shouldn't produce side effects

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")
Alist = AList.Select(
    Function(a, i)
        ' the assignment is now inside the selector, which is not what
        ' the selector is meant to do which is transform the elements
        a.Value = valueList(i)
        Return i
    End Function).ToList()
AList.ForEach(Sub(a) Console.WriteLine(a.Value))

This probably wouldn't feel right to most developers

djv
  • 15,168
  • 7
  • 48
  • 72