如何使用List(Of t)填充DataTable或将List(Of t)转换为DataTable?

时间:2009-11-26 21:04:46

标签: vb.net datatable structure generic-list

我已经阅读了很多关于这个主题的帖子;其中以及最近.NET - Convert Generic Collection to Data Table。不幸的是,一切都没有用。

我有一个通用的结构集合:

Private Structure MyStruct
Dim sState as String
Dim lValue as Long
Dim iLayer as Integer
End Structure

Dim LOStates As New List(Of MyStruct)

我需要使用此结构列表填充DataTable,但不知道如何执行此操作。我在Visual Studio 2008中使用vb.net。

非常感谢任何见解

3 个答案:

答案 0 :(得分:16)

您链接的代码假定成员被声明为属性。您没有声明属性。你可以使用Reflection:

Imports System.Reflection
...

      Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
        Dim table As New DataTable()
        Dim fields() As FieldInfo = GetType(T).GetFields()
        For Each field As FieldInfo In fields
          table.Columns.Add(field.Name, field.FieldType)
        Next
        For Each item As T In list
          Dim row As DataRow = table.NewRow()
          For Each field As FieldInfo In fields
            row(field.Name) = field.GetValue(item)
          Next
          table.Rows.Add(row)
        Next
        Return table
      End Function

答案 1 :(得分:2)

我遇到与@SamSelikoff相同的问题,转移到GetProperties:

Public Shared Function ConvertToDataTable(Of t)(
                                                  ByVal list As IList(Of t)
                                               ) As DataTable
    Dim table As New DataTable()
    If Not list.Any Then
        'don't know schema ....
        Return table
    End If
    Dim fields() = list.First.GetType.GetProperties
    For Each field In fields
        table.Columns.Add(field.Name, field.PropertyType)
    Next
    For Each item In list
        Dim row As DataRow = table.NewRow()
        For Each field In fields
            dim p = item.GetType.GetProperty(field.Name)
            row(field.Name) = p.GetValue(item, Nothing)
        Next
        table.Rows.Add(row)
    Next
    Return table
End Function

答案 2 :(得分:0)

如果有人正在处理可为空的类型,请使用@Hans Passant函数:

For Each field As FieldInfo In fields
' Extra check for nullable
If field.FieldType.AssemblyQualifiedName.Contains("System.Nullable") Then
    ' Insert proper type
    If field.FieldType.AssemblyQualifiedName.Contains("System.DateTime") Then
       table.Columns.Add(field.Name, Type.GetType("System.DateTime"))
    End If
Else
    table.Columns.Add(field.Name, field.FieldType)
End If
Next

值:

For Each item As T In list
Dim row As DataRow = table.NewRow()
For Each field As FieldInfo In fields
    ' Check if value is null
    If field.GetValue(item) is nothing Then
        Continue For
    End If
    row(field.Name) = field.GetValue(item)
Next
table.Rows.Add(row)
Next
相关问题