vb.net create objects in for each loop from partial info in Ienumerable

289 views Asked by At

Summary:I want to create objects in a for each loop.

I have a class - Dashboard, which has some properties - length, height, etc.

This info is contained within an XML document, but my class' properties is only a small subset of the information in the XML.

I have created a Collection of XElement, and I can iterate over these, but how do I create my object on each iteration of the loop?

Dim Col_DashBoards As IEnumerable(Of XElement) = From XDashboard In XDocument.Load(filename).Descendants("dashboard")
        For Each XDashboard In Col_DashBoards
            'PseudoCode
        Dim Xdashboard.Name as New DashboardClassObject
            Xdashboard.Name.Height = XDashboard.Element("Height").value 
            ...
        Next
1

There are 1 answers

0
IronAces On

If I have understood your question correctly, you wish to create a new object based on a subset of data from within an XML document?

The below is a function that will generate a new DashboardClassObject for every matching node and populate that object. A list of type DashboardclassObject is returned.

Public Function GenerateDashBoardFromXML(filename as string) As List(Of DashboardClassObject)
   Dim dashboardList As List(Of DashboardClassObject) = New List(Of DashboardClassObject)()
   Dim Col_DashBoards As IEnumerable(Of XElement) = From XDashboard In XDocument.Load(filename)?.Descendants("dashboard")

   For Each XDashboard In Col_DashBoards
       Dim dashboard As DashboardClassObject = New DashboardClassObject () With {
           .Name = XDashboard.Element("Height")?.value 
       }
       dashboardList.Add(dashboard)
   Next

   return dashboardList
End Function

It should be noted that Null checking is used here. The below is only populated if the matching element is found. Null coalescing operator is also an option here.

.Name = XDashboard.Element("Height")?.value