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

by Craig Bailey on August 24, 2008

in Microsoft

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…)

Kinda related posts:

  1. WordPress Pretty Permalinks on IIS 7.0
  2. TECHED: Web futures, SQL tips, LINQ to Entities, The future of IT
  3. CLARITY: SQL Server 2008

{ 1 comment… read it below or add one }

Andrew November 3, 2008 at 9:52 am

I have a similar issue, did you end up finding a better solution. I would have expected it to be quite easy??

Reply

Leave a Comment

Previous post:

Next post: