Friday, May 30, 2008

I needed a quick and dirty way to get my LinqToSQL results into a datatable due to a constraint by a component we were using. I couldn't find a decent mechanism for doing so within IQueryable, so I extended the following ToDataTable method. Any comments would be greatly appreciated.

<Extension()> _
Public Function ToDataTable(ByVal o As IQueryable) As DataTable

    Dim dt As New DataTable
    Dim props = o.ElementType.GetProperties
    For Each prop In props
        'Datatable doesn't like System.Nullable as a type, so I accounted for the two nullable fields I was using...
        If prop.PropertyType Is GetType(System.Nullable(Of DateTime)) Then
            dt.Columns.Add(New DataColumn(prop.Name, GetType(DateTime)))
        ElseIf prop.PropertyType Is GetType(System.Nullable(Of Integer)) Then
            dt.Columns.Add(New DataColumn(prop.Name, GetType(Integer)))
        Else
            dt.Columns.Add(New DataColumn(prop.Name, prop.PropertyType))
        End If
    Next
    For Each obj In (From x In o Select x)
        Dim oRow = dt.NewRow
        For Each prop In props
            If prop.GetValue(obj, Nothing) Is Nothing Then
                ' Don't set it to anything!!!
            Else
                oRow(prop.Name) = prop.GetValue(obj, Nothing)
            End If
        Next
        dt.Rows.Add(oRow)
    Next
    Return dt
End Function

kick it on DotNetKicks.com

posted on 5/30/2008 10:35:55 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]
  • Blog reactions