LINQ: Converting LINQ results to an XML file (via a DataTable)

L

I need some help with this one please…

I’m sure this is basic stuff but I’ve been fighting VB.NET a little lately as I try to get clever with some Outlook add-ins I’m writing (Disclaimer: I’m in *management* now so I don’t write code much these days :-)

Anyway I have a pretty simple requirement: I want to store my LINQ result set to an XML file. What’s the easiest way to do this?

Here’s my long winded work around that requires converting the Linq query to a Datatable and then using that to save to file… Here’s the conversion…

    Private Function LINQToDataTable(ByVal iEn As IEnumerable) As DataTable
 
        Dim dt As DataTable = New DataTable()
        dt.TableName = "LINQDataTable"
 
        For Each obj As Object In iEn
            Dim t As Type = obj.GetType()
            Dim props As PropertyInfo() = t.GetProperties()
 
            If dt.Columns.Count = 0 Then
                For Each p As PropertyInfo In props
                    dt.Columns.Add(p.Name, p.PropertyType)
                Next
            End If
 
            Dim dr As DataRow = dt.NewRow()
 
            For Each p As PropertyInfo In props
                Dim value As Object = p.GetValue(obj, Nothing)
                dr(p.Name) = value
            Next
            dt.Rows.Add(dr)
        Next
 
        Return dt
 
    End Function

And then I call it with something like this (sessionByTime is my Linq result set):

        Dim dt1 As DataTable = LINQToDataTable(sessionsByTime)
 
        Dim writer As New System.IO.StringWriter
        dt1.WriteXml(writer, XmlWriteMode.WriteSchema, False)
 
        WriteToFile(writer.ToString(), "c:\OBA\sessions.xml")

 

Can someone please tell me a better way to do this (preferably in one line of code)? In VB please. I asked around and tried a few forums, but couldn’t come up with a good answer.

And now back to my regular posts (I promise not to bore you with coding on this blog again…)

2 comments

About Craig

I'm the co-host of HubShots and the CEO of XEN - helping mid-large B2B companies with their digital marketing and lead generation.

Craig Bailey

Archives

Posts

BERT