1

I found this code on another answered question C# - How to xml deserialize object itself? I really like this code and want to use it in my application but I target the .net 2.0 Compact framework, so I cant use the LINQ expressions. Is there anyone who can tell me how I can convert this into "Normal VB" code?

Original code from from user wheelibin.

I went for this approach:

Public Class SerialisableClass

    Public Sub SaveToXML(ByVal outputFilename As String)
        Dim xmls = New System.Xml.Serialization.XmlSerializer(Me.GetType)
        Using sw = New IO.StreamWriter(outputFilename)
            xmls.Serialize(sw, Me)
        End Using
    End Sub

    Private tempState As Object = Me
    Public Sub ReadFromXML(ByVal inputFilename As String)
        Dim xmls = New System.Xml.Serialization.XmlSerializer(Me.GetType)

        Using sr As New IO.StreamReader(inputFilename)
            tempState = xmls.Deserialize(sr)
        End Using

        For Each pi In tempState.GetType.GetProperties()
            Dim name = pi.Name

            '  THIS IS THE PART THAT i CANT FIGURE OUT (HOW TO DO THIS WITHOUT LINQ)
            Dim realProp = (From p In Me.GetType.GetProperties
                            Where p.Name = name And p.MemberType = Reflection.MemberTypes.Property).Take(1)(0)
            '  -------------------------------------------------------------
            realProp.SetValue(Me, pi.GetValue(tempState, Nothing), Nothing)
        Next
    End Sub
End Class
Community
  • 1
  • 1
Rob Heijligers
  • 193
  • 1
  • 2
  • 9

1 Answers1

3

You can replace that LINQ part with "normal" For Each loop, for example :

Dim realProp As PropertyInfo
For Each p As PropertyInfo In Me.GetType.GetProperties()
    If p.Name = Name And p.MemberType = Reflection.MemberTypes.Property Then
    'set `realProp` with the first `p` that fulfil above `If` criteria'
    'this is equivalent to what your LINQ (...).Take(1)(0) does'
        realProp = p
        Exit For
    End If
Next
har07
  • 88,338
  • 12
  • 84
  • 137