Convert generic List/Enumerable to DataTable?

后端 未结 27 2150
臣服心动
臣服心动 2020-11-21 23:20

I have few methods that returns different Generic Lists.

Exists in .net any class static method or whatever to convert any list into a datatable? The only thing tha

27条回答
  •  离开以前
    2020-11-21 23:43

    Marc Gravell's answer but in VB.NET

    Public Shared Function ToDataTable(Of T)(data As IList(Of T)) As DataTable
        Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
        Dim table As New DataTable()
        For i As Integer = 0 To props.Count - 1
                Dim prop As PropertyDescriptor = props(i)
                table.Columns.Add(prop.Name, prop.PropertyType)
        Next
        Dim values As Object() = New Object(props.Count - 1) {}
        For Each item As T In data
                For i As Integer = 0 To values.Length - 1
                        values(i) = props(i).GetValue(item)
                Next
                table.Rows.Add(values)
        Next
        Return table
    End Function
    

提交回复
热议问题